|
1 | | -## Put comments here that give an overall description of what your |
2 | | -## functions do |
| 1 | +## Below are two functions, makeCacheMatrix and cacheSolve, which together allow for caching of the inverse of a matrix, so that you don't have to solve for the inverse (which is expensive) if you have already computed this. |
3 | 2 |
|
4 | | -## Write a short comment describing this function |
5 | 3 |
|
6 | | -makeCacheMatrix <- function(x = matrix()) { |
| 4 | +## makeCacheMatrix creates a matrix object which has functions allowing the user to get the value of the matrix itself, set it, get the "cached" inverse of the matrix, and set the cached inverse of the matrix. |
7 | 5 |
|
| 6 | +makeCacheMatrix <- function(x = matrix()) { |
| 7 | + inv <- NULL ## Sets inverse to NULL when you first make the cached entry |
| 8 | + |
| 9 | + ## Define a set function which sets the value of the vector and re-sets cached inverse to NULL (since you've changed the vector, the previous inverse is no longer valid) |
| 10 | + set <- function(y) { |
| 11 | + x <<- y |
| 12 | + inv <<- NULL |
| 13 | + } |
| 14 | + get <- function() x ## get function returns the value of the vector |
| 15 | + setinverse <- function(i) inv <<- i ## Sets the cached value of the inverse of x to i |
| 16 | + getinverse <- function() inv ## Returns the value of the cached inverse |
| 17 | + |
| 18 | + |
| 19 | + ## Return the four functions as elements of a list |
| 20 | + list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) |
| 21 | + |
8 | 22 | } |
9 | 23 |
|
10 | 24 |
|
11 | | -## Write a short comment describing this function |
| 25 | +## cacheSolve checks whether the matrix's inverse has already been computed, and if so, retrieves it; if not, computes it, caches it to the object as inv, and returns it. |
12 | 26 |
|
13 | 27 | cacheSolve <- function(x, ...) { |
14 | | - ## Return a matrix that is the inverse of 'x' |
| 28 | + inv <- x$getinverse() |
| 29 | + if (!is.null(inv)) { |
| 30 | + ## Then you just return the inverse from cache |
| 31 | + message("getting cached data") |
| 32 | + return(inv) |
| 33 | + } |
| 34 | + ## Else, you compute the inverse |
| 35 | + data <- x$get() |
| 36 | + newInv <- solve(data, ...) |
| 37 | + x$setinverse(newInv) ## Set x's inverse to the newly computed inverse |
| 38 | + newInv |
| 39 | + |
15 | 40 | } |
0 commit comments