|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
| 1 | +## Custom matrix data type that allows caching of the matrix inverse. |
5 | 2 |
|
| 3 | +## Creates a 'cache matrix' object representing the matrix x. |
| 4 | +## |
| 5 | +## A 'cache matrix' is a list with four methods: getValue, setValue, |
| 6 | +## getInverse, and setInverse. The matrix value, x, is retrievable |
| 7 | +## by invoking the setValue method, and can be updated by invoking |
| 8 | +## setValue with the new value as its only parameter. The inverse of |
| 9 | +## the matrix can also be cached by passing the value to setInverse |
| 10 | +## (no validation is performed) and retrieved by calling getInvsere. |
| 11 | +## Calls to setValue invalidate the cached inverse, setting it to NULL. |
6 | 12 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 13 | + # Closure variable for caching the inverse |
| 14 | + inverse <- NULL |
| 15 | + |
| 16 | + setValue <- function(newX) { |
| 17 | + x <<- newX |
| 18 | + message('matrix changed; invalidating cached inverse (if any)') |
| 19 | + inverse <<- NULL |
| 20 | + } |
| 21 | + |
| 22 | + getValue <- function() { |
| 23 | + x |
| 24 | + } |
| 25 | + |
| 26 | + setInverse <- function(newInverse) { |
| 27 | + message('setting cached inverse') |
| 28 | + inverse <<- newInverse |
| 29 | + } |
| 30 | + |
| 31 | + getInverse <- function() { |
| 32 | + inverse |
| 33 | + } |
| 34 | + |
| 35 | + # This is exactly analagous to the so-called "revealing module pattern" used in Javascript: |
| 36 | + # |
| 37 | + # function makeObject() { |
| 38 | + # function myMethod() { |
| 39 | + # return doStuff(); } |
| 40 | + # } |
| 41 | + # |
| 42 | + # return { |
| 43 | + # myMethod: myMethod |
| 44 | + # }; |
| 45 | + # } |
| 46 | + # // later: |
| 47 | + # obj = makeObject(); obj.myMethod(); // does stuff |
| 48 | + |
| 49 | + list(setValue=setValue, getValue=getValue, getInverse=getInverse, setInverse=setInverse) |
8 | 50 | }
|
9 | 51 |
|
10 | 52 |
|
11 |
| -## Write a short comment describing this function |
| 53 | +## Given a 'cache matrix' object, x, returns the inverse of the matrix |
| 54 | +## represented by x. If a cached value of the inverse exists, it is used; if there |
| 55 | +## is no cache value, the inverse (as computed by solve()) is cached into x. |
| 56 | +## Throws if the matrix is singular. |
12 | 57 |
|
13 | 58 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 59 | + inverse <- x$getInverse() |
| 60 | + |
| 61 | + if (!is.null(inverse)) { |
| 62 | + message('using cached inverse') |
| 63 | + return(inverse) |
| 64 | + } |
| 65 | + |
| 66 | + xValue <- x$getValue() |
| 67 | + inverse <- solve(xValue) |
| 68 | + x$setInverse(inverse) |
| 69 | + inverse |
15 | 70 | }
|
0 commit comments