|
1 | 1 | ## Put comments here that give an overall description of what your
|
2 | 2 | ## functions do
|
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +## Creates a special type of matrix object, called a CacheMatrix, |
| 5 | +## which can cache its inverse matrix. |
5 | 6 |
|
6 | 7 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 8 | + cacheMatrix <- NULL |
| 9 | + inverseMatrix <- NULL |
| 10 | + |
| 11 | + set <- function(aMatrix) { |
| 12 | + cacheMatrix <<- aMatrix |
| 13 | + inverseMatrix <<- NULL |
| 14 | + } |
| 15 | + |
| 16 | + get <- function() x |
| 17 | + |
| 18 | + setInverse <- function(inverse) inverseMatrix <<- inverse |
| 19 | + |
| 20 | + getInverse <- function() inverseMatrix |
| 21 | + |
| 22 | + list(set = set, get = get, |
| 23 | + setInverse = setInverse, |
| 24 | + getInverse = getInverse) |
| 25 | + |
8 | 26 | }
|
9 | 27 |
|
10 | 28 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 29 | +## Computes the inverse of a CacheMatrix, which is a matrix returned by makeCacheMatrix. |
| 30 | +## If the matrix has not changed since the last call to cacheSolve, a cached copy of |
| 31 | +## the inverse matrix will be returned, otherwise the inverse is computed, cached |
| 32 | +## and returned. |
| 33 | +## |
| 34 | +## PreCondition: The matrix, x, is invertible |
13 | 35 | cacheSolve <- function(x, ...) {
|
14 | 36 | ## Return a matrix that is the inverse of 'x'
|
| 37 | + |
| 38 | + inv <- x$getInverse() |
| 39 | + if (!is.null(inv)) { |
| 40 | + message("getting cached data") |
| 41 | + return(inv) |
| 42 | + } |
| 43 | + |
| 44 | + # get the inverse |
| 45 | + data <- x$get() |
| 46 | + inv <- solve(data) |
| 47 | + |
| 48 | + x$setInverse(inv) # cache inv |
| 49 | + |
| 50 | + inv # returns inv |
15 | 51 | }
|
0 commit comments