|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## These functions allow one to calculate and cache a matrix inverse, |
| 2 | +## avoiding the need to recalculate the inverse if it is needed multiple times. |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
| 4 | +### Example: |
| 5 | +### > source("./cachematrix.R") |
| 6 | +### > mymat <- makeCacheMatrix(matrix(c(1,2,3,3,2,1,4,5,2),ncol=3,nrow=3)) |
| 7 | +### > cacheSolve(mymat) |
| 8 | +### [,1] [,2] [,3] |
| 9 | +### [1,] -0.0625 -0.125 0.4375 |
| 10 | +### [2,] 0.6875 -0.625 0.1875 |
| 11 | +### [3,] -0.2500 0.500 -0.2500 |
| 12 | +### |
| 13 | +### > cacheSolve(mymat) |
| 14 | +### getting cached data |
| 15 | +### [,1] [,2] [,3] |
| 16 | +### [1,] -0.0625 -0.125 0.4375 |
| 17 | +### [2,] 0.6875 -0.625 0.1875 |
| 18 | +### [3,] -0.2500 0.500 -0.2500 |
5 | 19 |
|
| 20 | + |
| 21 | +## This creates the matrix object that will store the cached inverse, and a method to calculate the inverse |
6 | 22 | makeCacheMatrix <- function(x = matrix()) {
|
| 23 | + i <- NULL |
| 24 | + set <- function(y) { |
| 25 | + x <<- y |
| 26 | + i <<- NULL |
| 27 | + } |
| 28 | + get <- function() x |
| 29 | + setinv <- function(inv) i <<- inv |
| 30 | + getinv <- function() i |
7 | 31 |
|
| 32 | + return( list(set = set, get = get, |
| 33 | + setinv = setinv, |
| 34 | + getinv = getinv) ) |
8 | 35 | }
|
9 | 36 |
|
10 | 37 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 38 | +## This function will return the inverse of a matrix, via the cached value if possible |
13 | 39 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 40 | + ## Return a matrix that is the inverse of 'x' |
| 41 | + |
| 42 | + i <- x$getinv() |
| 43 | + if(!is.null(i)) { |
| 44 | + message("getting cached data") |
| 45 | + return(i) #if we already cached inverse then return and stop here |
| 46 | + } |
| 47 | + #otherwise calculate and cache inverse |
| 48 | + data <- x$get() |
| 49 | + i <- solve(data, ...) #solve for inverse - R function |
| 50 | + x$setinv(i) #cache inverse |
| 51 | + return(i) |
15 | 52 | }
|
0 commit comments