|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +# ------------------------------------------------------------------------------ |
| 2 | +# Helper functions to compute and cache the inverse of a matrix (i.e. "solve" a |
| 3 | +# matrix). |
| 4 | +# |
| 5 | +# Note: we assume a square matrix (i.e. one that is invertible) is always |
| 6 | +# provided when using these functions. Therefore there is no erro handling for |
| 7 | +# cases where this is not true. |
| 8 | +#------------------------------------------------------------------------------- |
3 | 9 |
|
4 |
| -## Write a short comment describing this function |
5 | 10 |
|
| 11 | +# Given an initial matrix, this method returns a special wrapper, in the form of |
| 12 | +# a list with functions that can be used to: |
| 13 | +# - set the underlying matrix again |
| 14 | +# - get the underlying matrix |
| 15 | +# - set the inverse of the underlying matrix |
| 16 | +# - get th inverse of the underlying matrix |
6 | 17 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 18 | + i <- NULL # Cache value for the inverse matrix of `x` |
| 19 | + |
| 20 | + # Setter method, if we want to overwrite the underlying matrix `x` |
| 21 | + set <- function(y) { |
| 22 | + x <<- y |
| 23 | + i <<- NULL |
| 24 | + } |
| 25 | + |
| 26 | + # Getter method, to access the underlying matrix `x` |
| 27 | + get <- function() { |
| 28 | + x |
| 29 | + } |
| 30 | + |
| 31 | + # Set the inverse of the underlying matrix `x`, into the cache |
| 32 | + setinverse <- function(inverse) { |
| 33 | + i <<- inverse |
| 34 | + } |
| 35 | + |
| 36 | + # Get the inverse of the underlying matrix `x`, from the cache |
| 37 | + # Note: this will return `NULL` if the cache hasn't been set yet |
| 38 | + getinverse <- function() { |
| 39 | + i |
| 40 | + } |
| 41 | + |
| 42 | + list(set = set, get = get, |
| 43 | + setinverse = setinverse, |
| 44 | + getinverse = getinverse) |
8 | 45 | }
|
9 | 46 |
|
10 | 47 |
|
11 |
| -## Write a short comment describing this function |
12 |
| - |
| 48 | +# Use this method to "solve" (i.e. get the inverse) of a matrix, doing so in a |
| 49 | +# way that caches the very first computation of the inverse and uses the cache |
| 50 | +# subsequently. |
| 51 | +# |
| 52 | +# The argument `x` MUST be the special wrapper obtained from `makeCacheMatrix`. |
13 | 53 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 54 | + ## Return a matrix that is the inverse of 'x' |
| 55 | + |
| 56 | + # Try to get the cached value |
| 57 | + i <- x$getinverse() |
| 58 | + if(!is.null(i)) { |
| 59 | + message("getting cached data") |
| 60 | + return(i) |
| 61 | + } |
| 62 | + |
| 63 | + # … otherwise compute the inverse and cache |
| 64 | + data <- x$get() |
| 65 | + i <- solve(data, ...) |
| 66 | + x$setinverse(i) |
| 67 | + i |
15 | 68 | }
|
0 commit comments