Skip to content

Commit 8624dd9

Browse files
committed
Update cachematrix.R
1 parent 7f657dd commit 8624dd9

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

cachematrix.R

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,27 @@
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+
## This function creates a special "matrix" object that can cache its inverse.
62
makeCacheMatrix <- function(x = matrix()) {
7-
3+
inv <- NULL # initialize inverse as NULL
4+
set <- function(y) {
5+
x <<- y # assign new matrix value
6+
inv <<- NULL # reset inverse cache
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+
## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
1317
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
18+
inv <- x$getinverse()
19+
if(!is.null(inv)) {
20+
message("getting cached data")
21+
return(inv) # return cached inverse
22+
}
23+
data <- x$get()
24+
inv <- solve(data, ...) # compute inverse
25+
x$setinverse(inv) # cache the inverse
26+
inv
1527
}

0 commit comments

Comments
 (0)