|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## The pair of functions makeCacheMatrix() and cacheSolve() |
| 2 | +## allow an invertible matrix and its inverse to be cached. |
| 3 | +## The inversion function used is solve() |
3 | 4 |
|
4 |
| -## Write a short comment describing this function |
| 5 | +## makeCacheMatrix - returns a cacheable invertible matrix. |
| 6 | +## x: is an invertible matrix |
| 7 | +## set() stores the matrix |
| 8 | +## get() retrieves the matrix |
| 9 | +## setinverse caches the result of of the inversion function |
| 10 | +## getinverse retrieves any cached result |
5 | 11 |
|
6 | 12 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 13 | + inv <- NULL |
| 14 | + |
| 15 | + # store the matrix |
| 16 | + set <- function(mx){ |
| 17 | + x <<- mx |
| 18 | + inv <<- NULL |
| 19 | + } |
| 20 | + get <- function() x |
| 21 | + |
| 22 | + # cache the inverse matrix |
| 23 | + setinverse <- function(s) inv <<- s |
| 24 | + getinverse <- function() inv |
| 25 | + |
| 26 | + list(set = set, |
| 27 | + get = get, |
| 28 | + setinverse = setinverse, |
| 29 | + getinverse = getinverse) |
8 | 30 | }
|
9 | 31 |
|
10 | 32 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 33 | +## cacheSolve - returns the cached inverse of a matrix. |
| 34 | +## x: is a cacheable invertible matrix defined by calling |
| 35 | +## makeCacheMatrix(M), where M is an invertible matrix |
| 36 | +## |
| 37 | + |
13 | 38 | cacheSolve <- function(x, ...) {
|
14 | 39 | ## Return a matrix that is the inverse of 'x'
|
| 40 | + # get cached inverse if it exists |
| 41 | + inv <- x$getinverse() |
| 42 | + if(!is.null(inv)){ |
| 43 | + message("getting cached data") |
| 44 | + return(inv) |
| 45 | + } |
| 46 | + |
| 47 | + # create a cached inverse |
| 48 | + data <- x$get() # obtain the matrix |
| 49 | + inv <- solve(data, ...) # invert the matrix |
| 50 | + x$setinverse(inv) # cache the inverse |
| 51 | + inv |
15 | 52 | }
|
0 commit comments