|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## A pair of functions that allow cached computation of inverse matrices |
| 2 | +## Note: input matrices are assumed to be invertible |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +# Example Usage: |
| 5 | +# |
| 6 | +# > B <- matrix(c(2,2,3,2), ncol=2, nrow=2) |
| 7 | +# > x <- makeCacheMatrix(B) |
| 8 | +# cacheSolve(x) |
| 9 | +# |
5 | 10 |
|
| 11 | +# creates a cachematrix for an input matrix x. The result |
| 12 | +# of this function can then be passed to cacheSolve() in order |
| 13 | +# to compute the inverse of x such that repeated invocations |
| 14 | +# use a cached result. |
6 | 15 | makeCacheMatrix <- function(x = matrix()) {
|
7 | 16 |
|
8 |
| -} |
| 17 | + # this is the cached result |
| 18 | + inverse <- NULL |
| 19 | + |
| 20 | + # set the input matrix (this can be used to reuse the vector returned |
| 21 | + # by makeCacheMatrix for a different input matrix |
| 22 | + set <- function(y) { |
| 23 | + x <<- y |
| 24 | + inverse <<- NULL #make sure to clear cached result |
| 25 | + } |
| 26 | + |
| 27 | + # returns the input matrix |
| 28 | + get <- function() x |
| 29 | + |
| 30 | + # set the inverse matrix. |
| 31 | + setinverse <- function(i) inverse <<- i |
| 32 | + getinverse <- function() inverse |
| 33 | + list(set = set, get = get, |
| 34 | + setinverse = setinverse, |
| 35 | + getinverse = getinverse) |
9 | 36 |
|
| 37 | +} |
10 | 38 |
|
11 |
| -## Write a short comment describing this function |
12 | 39 |
|
| 40 | +# returns the inverse of a matrix x. x |
| 41 | +# must be a cachematrix obtained via makeCacheMatrix |
13 | 42 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 43 | + |
| 44 | + # did we compute the result before? |
| 45 | + result <- x$getinverse() |
| 46 | + |
| 47 | + if (is.null(result)){ |
| 48 | + # inverse has not been computed before, so compute it now |
| 49 | + matrix <- x$get() # this is the original input matrix |
| 50 | + result <- solve(matrix) # solve it |
| 51 | + x$setinverse(result) # cache the result in the cache matrix |
| 52 | + } |
| 53 | + |
| 54 | + result # return the result |
15 | 55 | }
|
0 commit comments