|
1 | 1 | ## Put comments here that give an overall description of what your
|
2 | 2 | ## functions do
|
3 | 3 |
|
4 |
| -## Write a short comment describing this function |
5 |
| - |
| 4 | +## function makeCacheMatrix returns a list of functions that provide |
| 5 | +## cache capabilities to input variable x |
6 | 6 | makeCacheMatrix <- function(x = matrix()) {
|
7 |
| - |
| 7 | + |
| 8 | + # Define a cache variable that is empty |
| 9 | + invCache <- NULL |
| 10 | + # Define function to set the value of x and to clear the cache |
| 11 | + set <- function(y) { |
| 12 | + x <<- y |
| 13 | + invCache <<- NULL |
| 14 | + } |
| 15 | + # Define the function to get the value of x, simply returning x |
| 16 | + get <- function() x |
| 17 | + # Define function to fill the cache |
| 18 | + setinv <- function(inv) invCache <<- inv |
| 19 | + # Define function to get the cache content |
| 20 | + getinv <- function() invCache |
| 21 | + # Return list of functions |
| 22 | + list(set = set, get = get, |
| 23 | + setinv = setinv, |
| 24 | + getinv = getinv) |
8 | 25 | }
|
9 | 26 |
|
10 | 27 |
|
11 |
| -## Write a short comment describing this function |
| 28 | +## Function cacheSolve returns the inverse of input matrix x (assumption |
| 29 | +## that x is always invertible). The inverse is cached if not done so |
| 30 | +## before, and if already cached this cache is returned directly and the |
| 31 | +## inverse calculation is skipped |
12 | 32 |
|
13 | 33 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 34 | + ## Return a matrix that is the inverse of 'x' |
| 35 | + # get the cached inverse of x |
| 36 | + inv <- x$getinv() |
| 37 | + # If the obtained cached is filled, return the cache |
| 38 | + if(!is.null(inv)) { |
| 39 | + message("getting cached data") |
| 40 | + return(inv) |
| 41 | + } |
| 42 | + # Apparently the cache was empty, now calculate the inverse |
| 43 | + data <- x$get() |
| 44 | + inv <- solve(data, ...) |
| 45 | + # Store the calculated inverse in the cache |
| 46 | + x$setinv(inv) |
| 47 | + # Return the inverse of x |
| 48 | + inv |
15 | 49 | }
|
0 commit comments