|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
5 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
7 |
| - |
8 |
| -} |
9 |
| - |
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
15 |
| -} |
| 1 | +## Class and companion function to store a matrix |
| 2 | +## together with its cached inverse |
| 3 | +## Kay Johansen |
| 4 | + |
| 5 | +## Create an object that contains a matrix |
| 6 | +## and a place to cache its inverse |
| 7 | +## This object does not calculate the inverse itself; |
| 8 | +## use the companion function cacheSolve() to do that |
| 9 | +makeCacheMatrix <- function(theMatrix = matrix()) { |
| 10 | + theInverse <- NULL |
| 11 | + |
| 12 | + set <- function(m) { |
| 13 | + theMatrix <<- m |
| 14 | + theInverse <<- NULL |
| 15 | + } |
| 16 | + |
| 17 | + get <- function() |
| 18 | + theMatrix |
| 19 | + |
| 20 | + setInverse <- function(inv) |
| 21 | + theInverse <<- inv |
| 22 | + |
| 23 | + getInverse <- function(inv) |
| 24 | + theInverse |
| 25 | + |
| 26 | + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) |
| 27 | +} |
| 28 | + |
| 29 | + |
| 30 | +## Returns the inverse of the matrix contained in the |
| 31 | +## cacheMatrix object |
| 32 | +## Uses the cached inverse if it's already cached, |
| 33 | +## otherwise, calls solve to calculate the inverse |
| 34 | +## and sets the cached value |
| 35 | +cacheSolve <- function(cacheMatrix, ...) { |
| 36 | + inv <- cacheMatrix$getInverse() |
| 37 | + if (!is.null(inv)) { |
| 38 | + message("cache hit") |
| 39 | + return(inv) |
| 40 | + } |
| 41 | + message("cache miss") |
| 42 | + m <- cacheMatrix$get() |
| 43 | + inv <- solve(m) |
| 44 | + cacheMatrix$setInverse(inv) |
| 45 | + inv |
| 46 | +} |
0 commit comments