|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Matrix inversion is usually a costly computation and there may be some benefit |
| 2 | +## to caching the inverse of a matrix rather than compute it repeatedly |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +## This function creates a special "matrix" object that can cache its inverse. |
5 | 5 |
|
6 | 6 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 7 | + inverse <- NULL |
| 8 | + set <- function(y) { |
| 9 | + x <<- y |
| 10 | + inverse <<- NULL |
| 11 | + } |
| 12 | + get <- function() x |
| 13 | + setInverse <- function(i) inverse <<- i |
| 14 | + getInverse <- function() inverse |
| 15 | + list(set = set, get = get, |
| 16 | + setInverse = setInverse, |
| 17 | + getInverse = getInverse) |
8 | 18 | }
|
9 | 19 |
|
10 | 20 |
|
11 |
| -## Write a short comment describing this function |
| 21 | +## This function computes the inverse of the special "matrix" |
| 22 | +## returned by makeCacheMatrix above. |
| 23 | +## If the inverse has already been calculated (and the matrix has not changed), |
| 24 | +## then the cachesolve should retrieve the inverse from the cache. |
12 | 25 |
|
13 | 26 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 27 | + ## Return a matrix that is the inverse of 'x' |
| 28 | + inverse <- x$getInverse() |
| 29 | + if(!is.null(inverse)) { |
| 30 | + message("getting cached data") |
| 31 | + return(inverse) |
| 32 | + } |
| 33 | + data <- x$get() |
| 34 | + inverse <- solve(x$get(), ...) |
| 35 | + x$setInverse(inverse) |
| 36 | + inverse |
15 | 37 | }
|
0 commit comments