|
2 | 2 | ## functions do
|
3 | 3 |
|
4 | 4 | ## Write a short comment describing this function
|
5 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 5 | +# creates a list to encapsulate a matrix with various helper functions for that matrix, particularly a caching mechanism |
| 6 | +# logic for the caching is not included here, this function only creates the data structure that will be used by separate |
| 7 | +# caching logic. |
| 8 | +# helper functions include: |
| 9 | +# getInverse: returns the matrix inverse (computation is cached automatically, no need to set the value manually...) |
| 10 | +# get and set: getting and setting the matrix object (setting clears the cached inverse) |
| 11 | +# makeCacheMatrix ssumes the matrix is always invertible |
| 12 | +makeCacheMatrix <- function(subjectMatrix = matrix()) { |
| 13 | + inverse <- NULL |
| 14 | + set <- function(newMatrix) { |
| 15 | + subjectMatrix <<- newMatrix |
| 16 | + inverse <<- NULL |
| 17 | + } |
| 18 | + |
| 19 | + get <- function() { |
| 20 | + subjectMatrix |
| 21 | + } |
| 22 | + |
| 23 | + getInverse <- function() { |
| 24 | + inverse |
| 25 | + } |
| 26 | + |
| 27 | + setInverse <- function(newInverse) { |
| 28 | + inverse <<- newInverse |
| 29 | + } |
| 30 | + |
| 31 | + # assign a reference to the function to the label of the same name |
| 32 | + list(set = set, get = get, getInverse = getInverse, setInverse = setInverse) |
7 | 33 |
|
8 | 34 | }
|
9 | 35 |
|
10 | 36 |
|
11 | 37 | ## Write a short comment describing this function
|
12 |
| - |
| 38 | +# a caching wrapper for the solve() command when being used to calculate the matrix inverse. |
| 39 | +# to be used in conjunction with makeCacheMatrix, expects a data structure defined by makeCacheMatrix() |
13 | 40 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 41 | + ## Return a matrix that is the inverse of 'x' |
| 42 | + |
| 43 | + if (is.null(x$getInverse())) { |
| 44 | + # compute and cache the matrix inverse |
| 45 | + message("cachematrix: cache empty, calculating inverse with solve()") |
| 46 | + x$setInverse(solve(x$get(), ...)) |
| 47 | + } else { |
| 48 | + #report that we're using a cached value |
| 49 | + message("cachematrix: using cached value") |
| 50 | + } |
| 51 | + |
| 52 | + # return the cached inverse |
| 53 | + x$getInverse() |
| 54 | + |
15 | 55 | }
|
0 commit comments