|
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 | +#################################################################### |
| 2 | +# makeCacheMatrix function |
| 3 | +# parameter x: a reference to a square matrix object (2x2, 3x3, etc) |
| 4 | +# return: an object representing the matrix with four methods |
| 5 | +# set(): sets a new matrix to the object and resets the inverse matrix |
| 6 | +# get(): gets the matrix |
| 7 | +# setInverse(): stores the inverse of the matrix |
| 8 | +# getInverse(): gets the inverse of the matrix (if calucated using cacheStore()) |
| 9 | +#################################################################### |
5 | 10 |
|
6 | 11 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 12 | + #initialize the inverse matrix to NULL |
| 13 | + inverseMatrix <- NULL |
| 14 | + |
| 15 | + #sets the internal matrix object and resets the inverse to NULL |
| 16 | + #so it gets re-calculated |
| 17 | + set <- function(y) { |
| 18 | + x <<- y |
| 19 | + inverseMatrix <<- NULL |
| 20 | + } |
| 21 | + |
| 22 | + #returns the internal matrix object |
| 23 | + get <- function() x |
| 24 | + |
| 25 | + #sets the inverse matrix |
| 26 | + setInverse <- function(inverse) inverseMatrix <<- inverse |
| 27 | + |
| 28 | + #returns the inverse matrix |
| 29 | + getInverse <- function() inverseMatrix |
| 30 | + |
| 31 | + #return the list of functions to the caller |
| 32 | + list(set = set, |
| 33 | + get = get, |
| 34 | + setInverse = setInverse, |
| 35 | + getInverse = getInverse) |
8 | 36 | }
|
9 | 37 |
|
10 | 38 |
|
11 |
| -## Write a short comment describing this function |
| 39 | +#################################################################### |
| 40 | +# cacheSolve function |
| 41 | +# parameter x: a reference to a makeCacheMatrix object |
| 42 | +# ...: additional solve() parameters |
| 43 | +# description: calculates and caches the inverse for a square matrix |
| 44 | +#################################################################### |
12 | 45 |
|
13 | 46 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 47 | + #first, attempt to get the inverse from the special matrix object |
| 48 | + inverse <- x$getInverse() |
| 49 | + |
| 50 | + #if the inverse was already cached, return the cached value |
| 51 | + if(!is.null(inverse)) { |
| 52 | + message("getting cached inverse") |
| 53 | + return(inverse) |
| 54 | + } |
| 55 | + |
| 56 | + #otherwise, get the original matrix object, and calculate the inverse |
| 57 | + data <- x$get() |
| 58 | + inverse <- solve(data, ...) |
| 59 | + |
| 60 | + #set/cache the inverse matrix on the object, so it doesn't get recalculated |
| 61 | + #every time |
| 62 | + x$setInverse(inverse) |
| 63 | + |
| 64 | + #return the inverse |
| 65 | + inverse |
| 66 | + |
15 | 67 | }
|
0 commit comments