|
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 | +## Here presented a pair of functions that cache the inverse of a matrix. |
3 | 4 |
|
4 |
| -## Write a short comment describing this function |
| 5 | +## "makeCacheMatrix" function creates a special "matrix" object that can cache its inverse. |
| 6 | +## This "matrix" is really a list containing a function to: |
| 7 | +## set the value of the matrix |
| 8 | +## get the value of the matrix |
| 9 | +## set the value of the inverse matrix |
| 10 | +## get the value of the inverse matrix |
5 | 11 |
|
6 | 12 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 13 | + inv <- NULL |
| 14 | + set <- function(y) { ## set the value of the matrix |
| 15 | + x <<- y |
| 16 | + inv <<- NULL |
| 17 | + } |
| 18 | + get <- function() x ## get the value of the matrix |
| 19 | + setinv <- function(solution) inv <<- solution ## set the value of the inverse matrix |
| 20 | + getinv <- function() inv ## get the value of the inverse matrix |
| 21 | + list(set = set, get = get, setinv = setinv, getinv = getinv) ## return the list |
8 | 22 | }
|
9 | 23 |
|
10 | 24 |
|
11 |
| -## Write a short comment describing this function |
| 25 | +## The following function calculates the inverse matrix of the special "matrix" created with the above function. |
| 26 | +## However, it first checks to see if the inverse matrix has already been calculated. |
| 27 | +## If so, it gets the result from the cache and skips the computation. |
| 28 | +## Otherwise, it calculates the inverse of the matrix and sets the value in the cache via the setinv function. |
12 | 29 |
|
13 | 30 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 31 | + inv <- x$getinv() # query the x matrix's cache |
| 32 | + if (!is.null(inv)) { # if there is already a value in the cache |
| 33 | + message("getting cached data") |
| 34 | + return(inv) # just return the cached value, no computation needed |
| 35 | + } |
| 36 | + data <- x$get() # if there's no value in the cache |
| 37 | + inv <- solve(data, ...) # compute inverse matrix |
| 38 | + x$setinv(inv) # save the result back to x's cache |
| 39 | + inv # return the result |
15 | 40 | }
|
0 commit comments