|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than computing it repeatedly |
3 | 2 |
|
4 |
| -## Write a short comment describing this function |
| 3 | +## This function creates a special "matrix" object that can cache its inverse. |
5 | 4 |
|
6 | 5 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 6 | + m <- NULL |
| 7 | + set <- function(y) { |
| 8 | + x <<- y |
| 9 | + m <<- NULL |
| 10 | + } |
| 11 | + get <- function() x |
| 12 | + setinverse <- function(inverse) m <<- inverse |
| 13 | + getinverse <- function() m |
| 14 | + list(set = set, get = get, |
| 15 | + setinverse = setinverse, |
| 16 | + getinverse = getinverse) |
8 | 17 | }
|
9 | 18 |
|
10 | 19 |
|
11 |
| -## Write a short comment describing this function |
| 20 | +## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. |
| 21 | +## If the inverse has already been calculated (and the matrix has not changed), |
| 22 | +## then cacheSolve should retrieve the inverse from the cache. |
| 23 | +### This is a bit dumb cache, as it doesn't take into consideration that '...' arguments that might have changed in the second call |
| 24 | +### and returns the first value, even though calling solve with extra arguments would error |
| 25 | +### e.g. solve(my_matrix, mean) |
| 26 | +### This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. |
| 27 | +### If the inverse has already been calculated (and the matrix has not changed), then cacheSolve should retrieve the inverse from the cache. |
| 28 | +### whereas: |
| 29 | +### cached = makeCacheMatrix(my_matrix) |
| 30 | +### cacheSolve(cached) gives an inverse |
| 31 | +### cacheSolve(cached, mean) second call gives the same result even though it should normally error |
| 32 | +### The solution would be to either hash all arguments or store them in a list that would be a key for getting cached martices, |
| 33 | +### but that is beyond this programming assignment. |
12 | 34 |
|
13 | 35 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 36 | + ## Return a matrix that is the inverse of 'x' |
| 37 | + m <- x$getinverse() |
| 38 | + if(!is.null(m)) { |
| 39 | + message("getting cached data") |
| 40 | + return(m) |
| 41 | + } |
| 42 | + data <- x$get() |
| 43 | + m <- solve(data, ...) |
| 44 | + x$setinverse(m) |
| 45 | + m |
15 | 46 | }
|
0 commit comments