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
47 lines (39 loc) · 1.59 KB
/
Copy pathcachematrix.R
File metadata and controls
47 lines (39 loc) · 1.59 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
47
### Functions to allow caching the inverse of a matrix. Implementation
### creates a closure over a given matrix; calls to the new object returns
### the cached value if available, otherwise generates the inverse and stores
### it for future calls.
# Helper function that creates a closure over a given matrix that allows the
# inverse of the matrix to be cached to potentially avoid expensive
# computations. The resulting object is a list containing four functions:
#
# set() to set the value of matrix; setting the contents clears the cache
# get() to return the matrix
# setinverse() to cache the inverse of when computed
# getinverse() to retrieve the cache value (will be NULL if yet to be
# computed)
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setinverse <- function(inverse) inv <<- inverse
getinverse <- function() inv
list(set = set, get = get, setinverse = setinverse,
getinverse = getinverse)
}
# Main function call to retrieve the inverse of a matrix. If the inverse was
# previously computed and cached, return the cached value. Otherwise,
# compute the inverse and cache the resulting value for future use.
cacheSolve <- function(x, ...) {
inv <- x$getinverse()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
data <- x$get()
inv <- solve(data, ...)
x$setinverse(inv)
inv
}