|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## |
| 2 | +## This is a pair of functions that work together to create and cache an |
| 3 | +## inverted matrix. |
| 4 | +## - makeCacheMatrix |
| 5 | +## - cacheSolve |
| 6 | +## |
| 7 | +## A matrix is added to che cache with makeCacheMatrix. The inverse is |
| 8 | +## either computed and stored in the cache or retrieved from the cache |
| 9 | +## with the cacheSolve function. |
| 10 | +## |
| 11 | +## Example: |
| 12 | +## |
| 13 | +## a <- matrix(1:4, 2, 2) |
| 14 | +## b <- makeCacheMatrix(a) |
| 15 | +## --- Now compute the inverse for the first time and store in c |
| 16 | +## c <- cacheSolve(b) |
| 17 | +## --- Do other stuff |
| 18 | +## --- Retrieve the cached inverse matrix |
| 19 | +## c <- cacheSolve(b) |
3 | 20 |
|
4 |
| -## Write a short comment describing this function |
5 | 21 |
|
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 22 | +## makeCacheMatrix - Create an object to compute and cache a matrix inverse |
| 23 | +## |
| 24 | +## Parameters |
| 25 | +## x - The matrix to take the inverse of |
| 26 | +## |
| 27 | +## Returns an object (list of functions) that can be used by the cacheSolve |
| 28 | +## to conpute and cache the inverse of the matrix. |
| 29 | +## |
7 | 30 |
|
| 31 | +makeCacheMatrix <- function(x = matrix()) { |
| 32 | + inv <- NULL |
| 33 | + set <- function(y) { |
| 34 | + x <<- y |
| 35 | + inv <<- NULL |
| 36 | + } |
| 37 | + get <- function() x |
| 38 | + setinv <- function(i) inv <<- i |
| 39 | + getinv <- function() inv |
| 40 | + list(set = set, get = get, setinv = setinv, getinv = getinv) |
8 | 41 | }
|
9 | 42 |
|
10 | 43 |
|
11 |
| -## Write a short comment describing this function |
| 44 | +## cacheSolve - Compute and cache the inverse of a matrix held in an object |
| 45 | +## created by makeCacheMatrix |
| 46 | +## |
| 47 | +## Parameters |
| 48 | +## x - The object created by makeCacheMatrix that contains the matrix |
| 49 | +## |
| 50 | +## Returns the inverse of the matrix as calculated by the solve) function. |
| 51 | +## This result may have been cached on a previous call. |
| 52 | +## |
12 | 53 |
|
13 | 54 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 55 | + ## Return a matrix that is the inverse of 'x' |
| 56 | + i <- x$getinv() |
| 57 | + if(!is.null(i)) { |
| 58 | + message("getting cached data") |
| 59 | + return(i) |
| 60 | + } |
| 61 | + message("computing inverse") |
| 62 | + data <- x$get() |
| 63 | + i <- solve(data, ...) |
| 64 | + x$setinv(i) |
| 65 | + i |
15 | 66 | }
|
0 commit comments