|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## A utility for repeatedly accessing inverted matrices. |
| 2 | +## Computing a matrix's inverse is potentially expensive, so |
| 3 | +## this utility is optimized to avoid repeating the |
| 4 | +## computation by caching the results. |
3 | 5 |
|
4 |
| -## Write a short comment describing this function |
5 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 6 | +## Example: |
| 7 | +## > cm <- makeCacheMatrix(m) # construct an invertable matrix |
| 8 | +## > cacheSolve(cm) # computes and returns the inverse of m |
| 9 | +## > cacheSolve(cm) # returns the inverse of m, avoiding recomputation |
| 10 | +## > cm$set(m2) # changes the matrix, and clears the cache |
| 11 | +## > cacheSolve(cm) # computes and returns the inverse of m2 |
7 | 12 |
|
| 13 | +## Construct a matrix that can be inversed multiple times. |
| 14 | +makeCacheMatrix <- function(original = matrix()) { |
| 15 | + cached_inverse <- NULL |
| 16 | + |
| 17 | + # overrides the original matrix and clears the cached inverse |
| 18 | + set <- function(replacement) { |
| 19 | + original <<- replacement |
| 20 | + cached_inverse <<- NULL |
| 21 | + } |
| 22 | + |
| 23 | + get <- function() original |
| 24 | + setInverse <- function(inverse) cached_inverse <<- inverse |
| 25 | + getInverse <- function() cached_inverse |
| 26 | + list(set = set, get = get, |
| 27 | + setInverse = setInverse, |
| 28 | + getInverse = getInverse) |
8 | 29 | }
|
9 | 30 |
|
10 | 31 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 32 | +## Efficiently access the inverse of a matrix constructed with makeCacheMatrix |
13 | 33 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 34 | + cached <- x$getInverse() |
| 35 | + |
| 36 | + if(!is.null(cached)) { |
| 37 | + message("cached:") |
| 38 | + return(cached) |
| 39 | + } |
| 40 | + |
| 41 | + # else calculate, set and return inverse |
| 42 | + i <- solve(x$get(), ...) |
| 43 | + x$setInverse(i) |
| 44 | + i |
15 | 45 | }
|
0 commit comments