Skip to content

Commit 21d9229

Browse files
committed
Caching the Inverse of a Matrix
1 parent 7f657dd commit 21d9229

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

cachematrix.R

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,34 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Assignment: Caching the Inverse of a Matrix
32

4-
## Write a short comment describing this function
3+
## Creates a special "matrix" object that can cache its inverse.
54

65
makeCacheMatrix <- function(x = matrix()) {
7-
6+
inv <- NULL
7+
set <- function(y) {
8+
x <<- y
9+
inv <<- NULL
10+
}
11+
get <- function() x
12+
setinverse <- function(inv) inv <<- inv
13+
getinverse <- function() inv
14+
list(set = set, get = get,
15+
setinverse = setinverse,
16+
getinverse = getinverse)
817
}
918

1019

11-
## Write a short comment describing this function
20+
## Computes the inverse of the special "matrix" returned by `makeCacheMatrix`
21+
## above. If the inverse has already been calculated (and the matrix has not
22+
## changed), then `cacheSolve` should retrieve the inverse from the cache.
1223

1324
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
25+
inv <- x$getinverse()
26+
if(!is.null(inv)) {
27+
message("getting cached data")
28+
return(inv)
29+
}
30+
data <- x$get()
31+
inv <- solve(data, ...)
32+
x$setinverse(inv)
33+
inv
1534
}

0 commit comments

Comments
 (0)