|
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 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 1 | +## Calculate the Inverse of a Matrix |
| 2 | +## Provide a caching mechanism to reduce computation costs |
7 | 3 |
|
| 4 | +## `makeCacheMatrix`: Create a matrix with a memoizable solution |
| 5 | +## |
| 6 | +## args:: *theMatrix* is just a matrix |
| 7 | +## |
| 8 | +## methods:: |
| 9 | +## $setMatrix - will (re)set the original matrix and clear the memoized solution |
| 10 | +## $getMatrix - returns the original matrix |
| 11 | +## $setSolution - sets the calculated solution |
| 12 | +## $getSolution - returns the calculated solution |
| 13 | +## $cacheHit - increment the cache hit counter |
| 14 | +## $getHits - returns the number of times there was a cache "hit" |
| 15 | +## and we skipped recomputing the solution |
| 16 | +makeCacheMatrix <- function(theMatrix = matrix()) { |
| 17 | + cachedSolution <- NULL |
| 18 | + cacheHits <- 0 |
| 19 | + |
| 20 | + setMatrix <- function(newMatrix) { |
| 21 | + theMatrix <<- newMatrix |
| 22 | + cachedSolution <<- NULL |
| 23 | + cacheHits <<- 0 |
| 24 | + } |
| 25 | + getMatrix <- function() theMatrix |
| 26 | + |
| 27 | + setSolution <- function(solution) cachedSolution <<- solution |
| 28 | + |
| 29 | + getSolution <- function() cachedSolution |
| 30 | + |
| 31 | + cacheHit <- function() { |
| 32 | + cacheHits <<- cacheHits + 1 |
| 33 | + } |
| 34 | + |
| 35 | + getHits <- function() cacheHits |
| 36 | + |
| 37 | + list(setMatrix = setMatrix, getMatrix = getMatrix, |
| 38 | + setSolution = setSolution, getSolution = getSolution, |
| 39 | + cacheHit = cacheHit, getHits = getHits) |
8 | 40 | }
|
9 | 41 |
|
10 | 42 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 43 | +## `cacheSolve`: Return a matrix that is the inverse of 'x' |
| 44 | +## |
| 45 | +## args:: *x* was created using `makeCacheMatrix` |
| 46 | +## The original matrix must be solveable, or else an error will raise |
| 47 | +## |
| 48 | +## Use the cached results if possible |
13 | 49 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 50 | + solution <- x$getSolution() |
| 51 | + if(!is.null(solution)) { |
| 52 | + x$cacheHit() |
| 53 | + return(solution) |
| 54 | + } |
| 55 | + solution <- solve(x$getMatrix(), ...) |
| 56 | + x$setSolution(solution) |
| 57 | + solution |
15 | 58 | }
|
0 commit comments