|
1 | | -## Put comments here that give an overall description of what your |
2 | | -## functions do |
| 1 | +## Defines functions that compute and cache the inverse of a matrix to improve |
| 2 | +## performance when the inverse is needed multiple times. |
3 | 3 |
|
4 | | -## Write a short comment describing this function |
| 4 | +## Wraps the given matrix to enable the caching of its inverse. Returns a |
| 5 | +## list with the ability to get/set the matrix and get/set its inverse. |
5 | 6 |
|
6 | 7 | makeCacheMatrix <- function(x = matrix()) { |
| 8 | + inv <- NULL |
7 | 9 |
|
8 | | -} |
| 10 | + ## Set a new matrix, and be sure to reset the |
| 11 | + ## cached inverse |
| 12 | + set <- function(y) { |
| 13 | + x <<- y |
| 14 | + inv <- NULL |
| 15 | + } |
| 16 | + |
| 17 | + ## Return the current matrix |
| 18 | + get <- function() x |
| 19 | + |
| 20 | + ## Cache the computed inverse |
| 21 | + setInverse <- function(i) { |
| 22 | + inv <<- i |
| 23 | + } |
9 | 24 |
|
| 25 | + ## Return the cached inverse |
| 26 | + getInverse <- function() inv |
| 27 | + |
| 28 | + ## Return a list with the functions as properties |
| 29 | + list( |
| 30 | + set=set, |
| 31 | + get=get, |
| 32 | + setInverse=setInverse, |
| 33 | + getInverse=getInverse |
| 34 | + ) |
| 35 | +} |
10 | 36 |
|
11 | | -## Write a short comment describing this function |
| 37 | +## Finds the inverse of a matrix constructed by makeCacheMatrix. Caches the |
| 38 | +## inverse and returns it. On repeat invocations, returns the cached value |
| 39 | +## without solving for the inverse again. |
12 | 40 |
|
13 | 41 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 42 | + ## Check if the inverse has been computed and cached |
| 43 | + inv <- x$getInverse() |
| 44 | + |
| 45 | + if(!is.null(inv)) { |
| 46 | + ## If so, return it without recomputing it |
| 47 | + return(inv) |
| 48 | + } |
| 49 | + |
| 50 | + ## Fetch the matrix from its wrapping |
| 51 | + m <- x$get() |
| 52 | + |
| 53 | + ## Compute the inverse of the given matrix, passing through any additional |
| 54 | + ## parameters given to the cacheSolve function |
| 55 | + inv <- solve(m, ...) |
| 56 | + |
| 57 | + ## Cache the inverse to avoid recomputing it next time |
| 58 | + x$setInverse(inv) |
| 59 | + |
| 60 | + ## Return the inverted matrix |
| 61 | + inv |
15 | 62 | } |
0 commit comments