Skip to content

Commit c9ff14d

Browse files
committed
Implement memoized matrix inverse.
1 parent 7f657dd commit c9ff14d

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

cachematrix.R

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
1+
## Creates a wrapped matrix that can memoize its inverse calculation.
62
makeCacheMatrix <- function(x = matrix()) {
7-
3+
inv <- NULL
4+
set <- function(y) {
5+
x <<- y
6+
inv <<- NULL
7+
}
8+
get <- function() x
9+
setinverse <- function(inverse) inv <<- inverse
10+
getinverse <- function() inv
11+
list(set = set, get = get,
12+
setinverse = setinverse,
13+
getinverse = getinverse)
814
}
915

10-
11-
## Write a short comment describing this function
12-
16+
## Memoized version of the matrix solve(x) function, which caches the result
17+
## of the inverse calculation.
1318
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
19+
## Return a matrix that is the inverse of 'x'
20+
inv <- x$getinverse()
21+
if(!is.null(inv)) {
22+
message("getting cached data")
23+
return(inv)
24+
}
25+
data <- x$get()
26+
inv <- solve(data, ...)
27+
x$setinverse(inv)
28+
inv
1529
}

0 commit comments

Comments
 (0)