|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Taking the inverse of a matrix can be a very expensive operation |
| 2 | +## for very large matricies. These methods allow one to cache |
| 3 | +## the expensive operation so that if called again, the value |
| 4 | +## will be retuned much faster. This technique is also known |
| 5 | +## as memoization in computer science. |
| 6 | +## |
| 7 | +## Example: |
| 8 | +## > testm <- makeCacheMatrix(matrix(c(2:5),2,2)) |
| 9 | +## > cacheSolve(testm) #expensive operation |
| 10 | +## > cacheSolve(testm) #cache hit on second run |
3 | 11 |
|
4 |
| -## Write a short comment describing this function |
5 | 12 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 13 | +## This function will create a special version of matrix |
| 14 | +## which will encapsulate the matrix value as well as the |
| 15 | +## inverse of the matrix. This contains getters and setters |
| 16 | +## for these values. |
7 | 17 |
|
| 18 | +makeCacheMatrix <- function(x = matrix()) { |
| 19 | + inv <- NULL |
| 20 | + set <- function(y) { |
| 21 | + x <<- y |
| 22 | + inv <<- NULL |
| 23 | + } |
| 24 | + get <- function() x |
| 25 | + setinv <- function(i) inv <<- i |
| 26 | + getinv <- function() inv |
| 27 | + |
| 28 | + list(set = set, get = get, |
| 29 | + setinv = setinv, |
| 30 | + getinv = getinv) |
8 | 31 | }
|
9 | 32 |
|
10 | 33 |
|
11 |
| -## Write a short comment describing this function |
| 34 | +## This will check to see if there is a cached inverse value. |
| 35 | +## If not found, the inverse will be calculated, caached and |
| 36 | +## returned. |
12 | 37 |
|
13 | 38 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 39 | + inv <- x$getinv() |
| 40 | + if (!is.null(inv)) { |
| 41 | + message("cache hit") |
| 42 | + return(inv) |
| 43 | + } |
| 44 | + data <- x$get() |
| 45 | + inv <- solve(data, ...) |
| 46 | + x$setinv(inv) |
| 47 | + inv |
15 | 48 | }
|
0 commit comments