|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
| 1 | +## Code which can be used to create a `cacheMatrix` object (enclosed |
| 2 | +## environment) whose inverse is stored with the object. |
5 | 3 |
|
| 4 | +## Returns a `cacheMatrix` object created from the argument matrix object. |
6 | 5 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 6 | + |
| 7 | + # create the environment for performing these operations |
| 8 | + |
| 9 | + # store the cached inverse |
| 10 | + i <- NULL |
| 11 | + |
| 12 | + # used to change or set the underlying matrix |
| 13 | + # it resets the cached inverse to NULL |
| 14 | + set <- function(y) { |
| 15 | + x <<- y |
| 16 | + i <<- NULL |
| 17 | + } |
| 18 | + |
| 19 | + # returns the underlying matrix |
| 20 | + get <- function() x |
| 21 | + |
| 22 | + # sets the cached inverse value |
| 23 | + setinv <- function(inv) i <<- inv |
| 24 | + |
| 25 | + |
| 26 | + # gets the cached inverse value |
| 27 | + getinv <- function() i |
| 28 | + |
| 29 | + # return the environment |
| 30 | + list(set = set, get = get, setinv = setinv, getinv = getinv) |
| 31 | + |
8 | 32 | }
|
9 | 33 |
|
10 | 34 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 35 | +## Returns the inverse of the underlying matrix inside a `cacheMatrix` object. |
| 36 | +## If the inverse has already been computed, it returns the already-computed |
| 37 | +## value. Otherwise, it computes the value of the inverse and stores it for |
| 38 | +## future use. |
13 | 39 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 40 | + |
| 41 | + # see if there is already a cached inverse |
| 42 | + i <- x$getinv() |
| 43 | + |
| 44 | + # if the cached inverse is not NULL, return it |
| 45 | + if(!is.null(i)) { |
| 46 | + message("getting cached data") |
| 47 | + return(i) |
| 48 | + } |
| 49 | + |
| 50 | + # get the underlying matrix object |
| 51 | + data <- x$get() |
| 52 | + |
| 53 | + # calculate its inverse |
| 54 | + i <- solve(data, ...) |
| 55 | + |
| 56 | + # cache inverse in the cacheMatrix object |
| 57 | + x$setinv(i) |
| 58 | + |
| 59 | + # return the calculated inverse |
| 60 | + i |
15 | 61 | }
|
0 commit comments