|
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 | +## Solving for the inverse of a given (non-singular) matrix |
| 2 | +## Subsequent calls will use a cached value for the inverse, if available |
5 | 3 |
|
| 4 | +## Initialize a matrix environment with caching, define interface functions |
6 | 5 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 6 | + # the inverse starts out undefined |
| 7 | + inverse <- NULL |
| 8 | + |
| 9 | + # save a new matrix |
| 10 | + set <- function(y) { |
| 11 | + x <<- y |
| 12 | + # the inverse of a new matrix will begin undefined |
| 13 | + inverse <<- NULL |
| 14 | + } |
| 15 | + |
| 16 | + # return the currently loaded matrix |
| 17 | + get <- function() x |
| 18 | + |
| 19 | + # save the inverse of the current matrix |
| 20 | + setinv <- function(inv) inverse <<- inv |
| 21 | + |
| 22 | + # return the inverse |
| 23 | + getinv <- function() inverse |
| 24 | + |
| 25 | + # when initialized, return the four subfunctions of this environment |
| 26 | + list(set = set, get = get, setinv = setinv, getinv = getinv) |
8 | 27 | }
|
9 | 28 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 29 | +## Takes a predefined matrix (from makeCacheMatrix) and returns its inverse |
| 30 | +## Will use a cached value if available, if not it will be solved for and saved |
13 | 31 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 32 | + # ask the matrix environment for a cached inverse |
| 33 | + inverse <- x$getinv() |
| 34 | + |
| 35 | + # check if the inverse is cached already, if so just return it |
| 36 | + if(!is.null(inverse)) { |
| 37 | + message("matrix inverse found in cache! let's use it") |
| 38 | + return(inverse) |
| 39 | + } |
| 40 | + |
| 41 | + # no cached value found, solve for the inverse |
| 42 | + message("matrix inverse NOT found in cache! we'll have to solve for it") |
| 43 | + matrix <- x$get() |
| 44 | + inverse <- solve(matrix, ...) |
| 45 | + |
| 46 | + # save the newly solved for inverse to the matrix environment |
| 47 | + x$setinv(inverse) |
| 48 | + |
| 49 | + # return the inverse as requested |
| 50 | + inverse |
15 | 51 | }
|
0 commit comments