|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## These functions take advantage of R's scoping rules to "cache" potentiall expensive |
| 2 | +## matrix inverse operations |
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
5 | 4 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
7 | 5 |
|
| 6 | +## makeCacheMatrix creates a special "matrix", which is a list of functions to: |
| 7 | +## set the value of the matrix |
| 8 | +## get the value of the matrix |
| 9 | +## set the value of the matrix's inverse |
| 10 | +## get the value of the matrix's inverse |
| 11 | +makeCacheMatrix <- function(x = matrix()) { |
| 12 | + i <- NULL |
| 13 | + |
| 14 | + set <- function(y){ |
| 15 | + x <<- y |
| 16 | + i <<- NULL |
| 17 | + } |
| 18 | + get <- function() x |
| 19 | + setinverse <- function(inverse) i <<- inverse |
| 20 | + getinverse <- function() i |
| 21 | + # returns a list of these functions |
| 22 | + list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) |
8 | 23 | }
|
9 | 24 |
|
10 | 25 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 26 | +## Calculates the inverse of a "matrix" created by makeCacheMatrix |
| 27 | +## If the inverse has already been calculated and cached, return it. |
| 28 | +## Otherwise: calcaulate, cache, and return it. |
13 | 29 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 30 | + ## Return a matrix that is the inverse of 'x' |
| 31 | + i <- x$getinverse() |
| 32 | + # already cached? return it |
| 33 | + if(!is.null(i)){ |
| 34 | + message("getting cached inverse") |
| 35 | + return(i) |
| 36 | + } |
| 37 | + |
| 38 | + data <- x$get() # get the matrix |
| 39 | + i <- solve(data) # calculate its inverse |
| 40 | + x$setinverse(i) # cache the inverse |
| 41 | + i # return it |
15 | 42 | }
|
0 commit comments