|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +# cachematrix.R |
| 2 | +# A suite of functions to cache time-consuming matrix inversion computations |
| 3 | +# |
| 4 | +# Defines a pseudo "matrix" class which manages the cache, |
| 5 | +# and a cacheSolve() function to compute the inverse. |
| 6 | +# |
| 7 | +# Example: |
| 8 | +# m1 <- makeCacheMatrix(matrix(rnorm(16), 4, 4)) |
| 9 | +# cacheSolve(m1) |
| 10 | +# |
| 11 | +# Based on https://github.com/rdpeng/ProgrammingAssignment2/blob/master/cachematrix.R |
3 | 12 |
|
4 |
| -## Write a short comment describing this function |
5 | 13 |
|
| 14 | +# Returns a special "matrix" object (list) that can cache its inverse. |
6 | 15 | makeCacheMatrix <- function(x = matrix()) {
|
| 16 | + cachedInverse <- NULL |
7 | 17 |
|
| 18 | + # Accessors to the underlying matrix data |
| 19 | + get <- function () x |
| 20 | + set <- function (newMatrix) { |
| 21 | + x <<- newMatrix |
| 22 | + cachedInverse <<- NULL |
| 23 | + } |
| 24 | + |
| 25 | + # Convenient way to call cacheSolve() |
| 26 | + getInverse <- function () cacheSolve(obj) |
| 27 | + |
| 28 | + getCachedInverse <- function () cachedInverse |
| 29 | + setCachedInverse <- function (inverse) cachedInverse <<- inverse |
| 30 | + obj <- list(get = get, |
| 31 | + set = set, |
| 32 | + getInverse = getInverse, |
| 33 | + getCachedInverse = getCachedInverse, |
| 34 | + setCachedInverse = setCachedInverse) |
8 | 35 | }
|
9 | 36 |
|
10 | 37 |
|
11 |
| -## Write a short comment describing this function |
| 38 | +# This function computes the inverse of the special "matrix" |
| 39 | +# returned by `makeCacheMatrix`. |
| 40 | +# |
| 41 | +# If the inverse has already been calculated (and the matrix has not changed), |
| 42 | +# then the cached result will be returned. |
| 43 | +# |
| 44 | +# Returns a matrix that is the inverse of 'x' |
| 45 | +cacheSolve <- function (x, ...) { |
| 46 | + inverse <- x$getCachedInverse() |
| 47 | + |
| 48 | + if (is.null(inverse)) { |
| 49 | + inverse <- solve(x$get()) |
| 50 | + x$setCachedInverse(inverse) |
| 51 | + } |
12 | 52 |
|
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 53 | + inverse |
15 | 54 | }
|
0 commit comments