Skip to content

Commit cec9765

Browse files
committed
Implementation of cacheSolve function
1 parent cbc64b9 commit cec9765

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

cachematrix.R

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,26 @@ makeCacheMatrix <- function(x = matrix()) {
3434
}
3535

3636

37-
## Write a short comment describing this function
38-
37+
# This function returns an inverse of the matrix. If the inverse is not already
38+
# computed, it will compute it and store in cache; otherwise, it will just return the value from cache
39+
# x must be the output of the makeCacheMatrix function
3940
cacheSolve <- function(x, ...) {
40-
## Return a matrix that is the inverse of 'x'
41+
# try to get cached value
42+
inverse <- x$getinverse()
43+
44+
# verify if inverse has ever been cached (NULL indicates it has not been computed yet)
45+
# if it has been computed; return cached value
46+
if(!is.null(inverse)) {
47+
message("getting cached data")
48+
return(inverse)
49+
}
50+
51+
# otherwise, compute the inverse and store in cache
52+
computedInverse <- solve(x$get())
53+
54+
# store computed value in cache
55+
x$setinverse(computedInverse)
56+
57+
# return the value
58+
computedInverse
4159
}

0 commit comments

Comments
 (0)