Skip to content

Commit 8337a63

Browse files
committed
Implement cacheSolve
cacheSolve takes in a cache matrix x and returns the matrix's inverse. x is a list created by the makeCacheMatrix function. If x has a previously calculated inverse, it is used as the return value. Otherwise, the inverse is calculated, stored in x, and returned.
1 parent 2f2cc77 commit 8337a63

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

cachematrix.R

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,20 @@ makeCacheMatrix <- function(x = matrix()) {
1717
}
1818

1919

20-
## Write a short comment describing this function
20+
## cacheSolve takes in a cache matrix x and returns the matrix's
21+
## inverse. x is a list created by the makeCacheMatrix function.
22+
## If x has a previously calculated inverse, it is used as the
23+
## return value. Otherwise, the inverse is calculated, stored
24+
## in x, and returned.
2125

2226
cacheSolve <- function(x, ...) {
23-
## Return a matrix that is the inverse of 'x'
27+
inv <- x$getinv()
28+
if (!is.null(inv)) {
29+
message("getting cached data")
30+
return(inv)
31+
}
32+
data <- x$get()
33+
inv <- solve(data, ...)
34+
x$setinv(inv)
35+
inv
2436
}

0 commit comments

Comments
 (0)