|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
5 |
| - |
| 1 | +## Create a matrix and lexically scoped function |
| 2 | +## Follow the code in the example for this assignment |
| 3 | +## ??? |
| 4 | +## Profit! |
| 5 | +## Pass in matrix, return list with setters and getters |
| 6 | +## test on example from forum: matrix(c(1,1,1,3,4,3,3,3,4),3,3) |
| 7 | +## more tests at https://class.coursera.org/rprog-009/forum/thread?thread_id=164 |
6 | 8 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 9 | + invertedMatrix <- NULL |
| 10 | + set <- function(y) { |
| 11 | + x <<- y |
| 12 | + invertedMatrix <<- NULL |
| 13 | + } |
| 14 | + get <- function() x |
| 15 | + setinverse <- function(inverse) invertedMatrix <<- inverse |
| 16 | + getinverse <- function() invertedMatrix |
| 17 | + list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) ## list with function closures! |
8 | 18 | }
|
9 | 19 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 20 | +## Use the R solve() function to invert a matrix - return prior results if cached |
13 | 21 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 22 | + ## Return a matrix that is the inverse of 'x' |
| 23 | + ## NO CHECKING for invertable matrix |
| 24 | + invertedMatrix <- x$getinverse() |
| 25 | + if (!is.null(invertedMatrix)) { ## if not null, we found a cache hit |
| 26 | + message("getting cached matrix") |
| 27 | + return(invertedMatrix) |
| 28 | + } else { ## cache miss; else clause clearer IMO |
| 29 | + invertedMatrix <- solve(x$get()) ## execute the function, don't return it |
| 30 | + x$setinverse(invertedMatrix) ## now set the cache so we don't recalculate on another invocation |
| 31 | + return(invertedMatrix) |
| 32 | + } |
15 | 33 | }
|
| 34 | + |
0 commit comments