Skip to content

Commit 9146a29

Browse files
committed
cache original matrix to detect whether it has changed (invalidate cache)
1 parent ac47bfa commit 9146a29

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

cachematrix.R

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,36 @@
99
## https://class.coursera.org/rprog-016/human_grading/view/courses/972581/assessments/3/submissions
1010

1111
## Return a list object that encapsulates a given matrix and its calculated inverse.
12-
## `x_inv' is the memoized variable that caches the inverse
12+
## `x_mat' keeps a reference to the given matrix (for comparison purposes)
13+
## `x_inv' is the memoized variable that caches the inverse of the matrix
1314
## `inverse' is an accessor function for the inverse of the given matrix (`x_inv')
14-
## `cache' is a function to set the value of `x_inv', and conveniently returns it
15+
## `cache' caches the given matrix along with its inverse, and conveniently returns the inverse
1516
makeCacheMatrix <- function(x = matrix()) {
17+
x_mat <- x
1618
x_inv <- NULL
1719
inverse <- function() x_inv
18-
cache <- function(inv) { x_inv <<- inv; x_inv }
19-
list(matrix = x, inverse = inverse, cache = cache)
20+
original <- function() x_mat
21+
cache <- function(mat, inv) {
22+
x_mat <<- mat
23+
x_inv <<- inv
24+
x_inv
25+
}
26+
list(matrix = x, inverse = inverse, cache = cache, original = original)
2027
}
2128

22-
## Returns the inverse of `x$matrix', potentially retrieving it from cache
29+
## Returns the inverse of `x$matrix', potentially retrieving it from cache.
30+
## If the matrix has changed, recompute the inverse and update the cache.
2331
cacheSolve <- function(x, ...) {
24-
if (!is.null(x$inverse())) {
25-
# message("cache hit")
32+
if (cacheIsValid(x)) {
33+
## message("cache hit")
2634
return(x$inverse())
2735
}
28-
x$cache(solve(x$matrix, ...)) # n.b. this *returns* the inverse in addition to caching it
36+
x$cache(x$matrix, solve(x$matrix, ...)) # n.b. this returns the inverse (in addition to caching it)
37+
}
38+
39+
## Return true if the cached matrix inverse is valid, requirements being:
40+
## 1. the inverse has previously been computed
41+
## 2. the underlying matrix for which the inverse was computed has not changed
42+
cacheIsValid <- function(m) {
43+
!is.null(m$inverse()) && m$matrix == m$original()
2944
}

0 commit comments

Comments
 (0)