|
2 | 2 | ## functions do |
3 | 3 |
|
4 | 4 | ## Write a short comment describing this function |
| 5 | +makeCacheMatrix is a function that creates a special matrix that can be used to cache |
| 6 | +its inverse, since matrix inversion can be time consuming. Instead of recalculating |
| 7 | +the inverse of a matrix, it will be stored in a cache for retrieval. |
5 | 8 |
|
6 | | -makeCacheMatrix <- function(x = matrix()) { |
| 9 | +makeCacheMatrix returns a list with a function to |
| 10 | +1. set the value of the matrix |
| 11 | +2. get the value of the matrix |
| 12 | +3. set the value of the matrix inverse |
| 13 | +4. get the value of the matrix inverse |
7 | 14 |
|
| 15 | +makeCacheMatrix <- function(x = matrix()) { |
| 16 | + m <- NULL |
| 17 | + set <- function(y) { |
| 18 | + x <<- y |
| 19 | + m <<- NULL |
| 20 | + } |
| 21 | + get <- function() x |
| 22 | + setmatrixInverse <- function(calcMatrixInverse) m <<- matrixInverse |
| 23 | + getmatrixInverse <- function() m |
| 24 | + list(set = set, get = get, |
| 25 | + setmatrixInverse = setmatrixInverse, |
| 26 | + getmatrixInverse = getmatrixInverse) |
8 | 27 | } |
9 | 28 |
|
10 | 29 |
|
11 | 30 | ## Write a short comment describing this function |
12 | 31 |
|
| 32 | +The following function calculates the matrix inverse of the special "vector" |
| 33 | +created with the above function. However, it first checks to see if the |
| 34 | +matrix inverse has already been calculated. If so, it `get`s the matrix inverse from the |
| 35 | +cache and skips the computation. Otherwise, it calculates the matrix inverse of |
| 36 | +the data and sets the value of the matrix inverse in the cache via the `setMatrixInverse` |
| 37 | +function. |
| 38 | + |
13 | 39 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 40 | + ## Return a matrix that is the inverse of 'x' |
| 41 | + m <- x$matrixInverse() |
| 42 | + if(!is.null(m)) { |
| 43 | + message("getting cached data") |
| 44 | + return(m) |
| 45 | + } |
| 46 | + data <- x$get() |
| 47 | + m <- calcMatrixInverse(data, ...) |
| 48 | + x$setmatrixInverse(m) |
| 49 | + m |
15 | 50 | } |
0 commit comments