|
9 | 9 | ## https://class.coursera.org/rprog-016/human_grading/view/courses/972581/assessments/3/submissions
|
10 | 10 |
|
11 | 11 | ## 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 |
13 | 14 | ## `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 |
15 | 16 | makeCacheMatrix <- function(x = matrix()) {
|
| 17 | + x_mat <- x |
16 | 18 | x_inv <- NULL
|
17 | 19 | 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) |
20 | 27 | }
|
21 | 28 |
|
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. |
23 | 31 | cacheSolve <- function(x, ...) {
|
24 |
| - if (!is.null(x$inverse())) { |
25 |
| - # message("cache hit") |
| 32 | + if (cacheIsValid(x)) { |
| 33 | + ## message("cache hit") |
26 | 34 | return(x$inverse())
|
27 | 35 | }
|
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() |
29 | 44 | }
|
0 commit comments