|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 |
| - |
4 |
| -## Write a short comment describing this function |
| 1 | +## Pair of functions that cache the inverse of a matrix |
| 2 | +## Usage: Pass the result of a makeCacheMatrix call to cacheSolve |
5 | 3 |
|
| 4 | +#' Util function that set the matrix and the inverse in an environment |
| 5 | +#' @param x an invertible matrix |
| 6 | +#' examples |
| 7 | +#' x = makeCacheMatrix(matrix(rnorm(9), 3, 3)) |
| 8 | +#' x$set(matrix(rnorm(16), 4, 4)) |
6 | 9 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 10 | + # todo error if x is not a matrix |
| 11 | + inv <- NULL |
| 12 | + set <- function(y) { |
| 13 | + x <<- y |
| 14 | + inv <<- NULL |
| 15 | + } |
| 16 | + get <- function() x |
| 17 | + setinverse <- function(inverse) inv <<- inverse |
| 18 | + getinverse <- function() inv |
| 19 | + list(set = set, get = get, |
| 20 | + setinverse = setinverse, |
| 21 | + getinverse = getinverse) |
8 | 22 | }
|
9 | 23 |
|
10 | 24 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 25 | +#' Compute and cache the inverse of a matrix |
| 26 | +#' @param x the result of a previous makeCacheMatrix call |
| 27 | +#' @param ... additional arguments to pass to solve function |
| 28 | +#' examples |
| 29 | +#' x = makeCacheMatrix(matrix(rnorm(9), 3, 3)) |
| 30 | +#' cacheSolve(x) |
13 | 31 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 32 | + ## Return a matrix that is the inverse of 'x' |
| 33 | + inv <- x$getinverse() |
| 34 | + if(!is.null(inv)) { |
| 35 | + message("getting cached matrix inverse") |
| 36 | + return(inv) |
| 37 | + } |
| 38 | + data <- x$get() |
| 39 | + inv <- solve(data, ...) |
| 40 | + x$setinverse(inv) |
| 41 | + inv |
15 | 42 | }
|
0 commit comments