forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
46 lines (38 loc) · 1.44 KB
/
Copy pathcachematrix.R
File metadata and controls
46 lines (38 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
## Wrap a matrix with functions so that its inverse will be calculated once and
## cached so it can be efficiently retrieved
## Given a matrix, wrap it with functions that will get and set the value and
## get and set the inverse
makeCacheMatrix <- function(x = matrix()) {
inverse <- NULL # store the cached inverse
# function to set the matrix and clear the inverse
set <- function(y) {
x <<- y
inverse <<- NULL
}
# function to get the matrix
get <- function() x
# function to set the inverse matrix
setinverse <- function(inv) inverse <<- inv
# function to get the inverse matrix
getinverse <- function() inverse
# return the list of functions
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## Pass a CacheMatrix (see makeCacheMatrix) which will return the inverse of the
## matrix, using the cached value if it has already been calculated, or
## calculates and caches the inverse before returning it
cacheSolve <- function(x, ...) {
## Return the cached inverse if available
inv <- x$getinverse()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
## cached inverse isn't available, calcluate and set it
data <- x$get() # get the matrix
inv <- solve(data) # get the inverse
x$setinverse(inv) # set the inverse
inv # return the inverse
}