|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## The provided functions create a matrix which knows how to |
| 2 | +## cache it's inverse when needed. |
| 3 | +## Usage: |
| 4 | +## m = makeCacheMatrix(mymatrix) |
| 5 | +## cacheSolve(m) # computes and caches on the first call |
| 6 | +## cacheSolve(m) # returns cache on subsequent calls |
3 | 7 |
|
4 |
| -## Write a short comment describing this function |
| 8 | + |
| 9 | +## Make a version of the matrix which is used to save the cache of the inverse |
5 | 10 |
|
6 | 11 | makeCacheMatrix <- function(x = matrix()) {
|
| 12 | + inverse.cache <- NULL |
| 13 | + set <- function(y) { |
| 14 | + x <<- y |
| 15 | + inverse.cache <<- NULL |
| 16 | + } |
| 17 | + get <- function() x |
| 18 | + setinverse <- function(inverse) inverse.cache <<- inverse |
| 19 | + getinverse <- function() inverse.cache |
7 | 20 |
|
| 21 | + # return the list of functions that allow the cache to be manipulated |
| 22 | + list(set = set, |
| 23 | + get = get, |
| 24 | + setinverse = setinverse, |
| 25 | + getinverse = getinverse) |
| 26 | + |
8 | 27 | }
|
9 | 28 |
|
10 | 29 |
|
11 |
| -## Write a short comment describing this function |
| 30 | +## Return the cached inverse of a matrix or |
| 31 | +## compute and cache the inverse if not cached. |
12 | 32 |
|
13 | 33 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 34 | + # see if we have the inverse cached |
| 35 | + inverse <- x$getinverse() |
| 36 | + if(!is.null(inverse)) { |
| 37 | + message("using cached inverse") |
| 38 | + } else { |
| 39 | + message("computing and caching inverse") |
| 40 | + # not cached, get the matrix and invert it |
| 41 | + data <- x$get() |
| 42 | + inverse <- solve(data, ...) |
| 43 | + # save the inverse in the cache |
| 44 | + x$setinverse(inverse) |
| 45 | + } |
| 46 | + inverse |
15 | 47 | }
|
0 commit comments