|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Set of functions to facilitate matrix inversion to reduce costly computation |
| 2 | +## involved with calculating inverse of the matrix |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +## Function: makeCacheMatrix |
| 5 | +## Arguments: x - a matrix (default: empty matrix) |
| 6 | +## Returns: A list containing a set of functions which perform operations on the |
| 7 | +## matrix as follows: |
| 8 | +## set: function to set the contents of vector |
| 9 | +## get: function to return the vector |
| 10 | +## setInverse: function that caches the inverse of the matrix |
| 11 | +## getInverse: function that returns a cached value of the matrix; NA if |
| 12 | +## not set. |
5 | 13 |
|
6 | 14 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 15 | + myInverse <- NULL |
| 16 | + set <- function(aMatrix) { |
| 17 | + x <<- aMatirx |
| 18 | + myInverse <<- NULL |
| 19 | + } |
| 20 | + get <- function() x |
| 21 | + setInverse <- function(anInverse) myInverse <<- anInverse |
| 22 | + getInverse <- function() myInverse |
| 23 | + list( set = set, get = get, setInverse = setInverse, getInverse = getInverse ) |
8 | 24 | }
|
9 | 25 |
|
10 | 26 |
|
11 |
| -## Write a short comment describing this function |
| 27 | +## Function: cacheSolve |
| 28 | +## Arguments: x: a matrix created by makeCacheMatrix function. |
| 29 | +## Returns: A matrix containing the inverse (Either from x's cached inverse, |
| 30 | +## or a freshly calculated one if none already exists. If it must |
| 31 | +## calculate a new inverse, it will also save that with x's setInverse |
| 32 | +## function for later retrieval) |
12 | 33 |
|
13 | 34 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 35 | + # Check if x already has a cached inverse |
| 36 | + myInverse <- x$getInverse() |
| 37 | + if(!is.null(myInverse)) { |
| 38 | + # It does have a cache, so return that |
| 39 | + message("Getting cached inverse Matrix") |
| 40 | + return(myInverse) |
| 41 | + } |
| 42 | + # No cached inverse, so get the matrix, and solve an inverse for it |
| 43 | + myMatrix <- x$get() |
| 44 | + myInverse <- solve(myMatrix) |
| 45 | + # Save the inverse to the cache |
| 46 | + x$setInverse(myInverse) |
| 47 | + # Return the inverse |
| 48 | + myInverse |
15 | 49 | }
|
0 commit comments