|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
| 1 | +## These two functions allow for caching the inverse of a matrix, to save |
| 2 | +## compuation time for this CPU intensive operation |
| 3 | +## For this, two functions are defined: |
| 4 | +## - makeCacheMatrix: allows for caching a matrix and its inverse |
| 5 | +## - cacheSolve: computing and storing the inverse |
3 | 6 |
|
4 |
| -## Write a short comment describing this function |
| 7 | +## allows for caching a matrix and its inverse |
5 | 8 |
|
6 | 9 | makeCacheMatrix <- function(x = matrix()) {
|
| 10 | + i <- NULL |
| 11 | + ## making sure that if a new matrix is set, we store its value |
| 12 | + ## and reset our inverse (since we haven't calculated it yet) |
| 13 | + set <- function(y) { |
| 14 | + x <<- y |
| 15 | + i <<- NULL |
| 16 | + } |
7 | 17 |
|
| 18 | + ## return the original base matrix |
| 19 | + get <- function() x |
| 20 | + |
| 21 | + ## set new value for the inverse |
| 22 | + setinv <- function(mat) i <<- mat |
| 23 | + |
| 24 | + ## return value of the inverse |
| 25 | + getinv <- function() i |
| 26 | + list(set = set, get = get, setinv = setinv, getinv = getinv) |
8 | 27 | }
|
9 | 28 |
|
10 | 29 |
|
11 |
| -## Write a short comment describing this function |
| 30 | +## This is the function to which we pass the function (which is really a list) |
| 31 | +## "makeCacheMatrix" and compute and store the inverse |
12 | 32 |
|
13 | 33 | cacheSolve <- function(x, ...) {
|
14 | 34 | ## Return a matrix that is the inverse of 'x'
|
| 35 | + i <- x$getinv() |
| 36 | + |
| 37 | + ## in case we already know the inverse, we skip recomputing it and return the cached value |
| 38 | + if(!is.null(i)) { |
| 39 | + message("getting cached inverse") |
| 40 | + return(i) |
| 41 | + } |
| 42 | + |
| 43 | + ## getting our base matrix ... |
| 44 | + data <- x$get() |
| 45 | + |
| 46 | + ## ... passing it to the R solver (making sure to catch any errors) ... |
| 47 | + i <- try(solve(data, ...)) |
| 48 | + |
| 49 | + ## ... and storing and displaying the result |
| 50 | + x$setinv(i) |
| 51 | + i |
15 | 52 | }
|
0 commit comments