|
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 | +# the functions below allow us to calculate the inverse of a matrix, |
| 2 | +# storing it in cache for faster calculations, assuming that the matrix |
| 3 | +# provided is always inversible |
5 | 4 |
|
6 | 5 | makeCacheMatrix <- function(x = matrix()) {
|
| 6 | + # this is where we store the cached calculation |
| 7 | + cachedMatrix <- NULL |
| 8 | + |
| 9 | + set <- function(y) { |
| 10 | + x <<- y |
| 11 | + cachedMatrix <<- NULL |
| 12 | + } |
| 13 | + |
| 14 | + # returns the original matrix |
| 15 | + get <- function() { |
| 16 | + return(x) |
| 17 | + } |
| 18 | + |
| 19 | + # stores the inverse matrix provided by the function |
| 20 | + setSolve <- function(m) { |
| 21 | + cachedMatrix <<- m |
| 22 | + } |
7 | 23 |
|
| 24 | + # returns the cached inverse matrix |
| 25 | + getSolve <- function() { |
| 26 | + return(cachedMatrix) |
| 27 | + } |
| 28 | + |
| 29 | + list(set = set, get = get, setSolve = setSolve, getSolve = getSolve) |
8 | 30 | }
|
9 | 31 |
|
| 32 | +# given a cachedMatrix created with makeCacheMatrix(matrix), this function will |
| 33 | +# calculate its inverse matrix |
| 34 | +# |
| 35 | +# example: |
| 36 | +# |
| 37 | +# > mat1 <- makeCacheMatrix(matrix(1:4, ncol=2, nrow=2)) |
| 38 | +# |
| 39 | +# > mat1$get() |
| 40 | +# [,1] [,2] |
| 41 | +# [1,] 1 3 |
| 42 | +# [2,] 2 4 |
| 43 | +# |
| 44 | +# First call (no cached results): |
| 45 | +# |
| 46 | +# > cacheSolve(mat1) |
| 47 | +# [,1] [,2] |
| 48 | +# [1,] -2 1.5 |
| 49 | +# [2,] 1 -0.5 |
10 | 50 |
|
11 |
| -## Write a short comment describing this function |
| 51 | +# Second call (cached results): |
| 52 | +# |
| 53 | +# > cacheSolve(mat1) |
| 54 | +# [1] "getting cached data" |
| 55 | +# [,1] [,2] |
| 56 | +# [1,] -2 1.5 |
| 57 | +# [2,] 1 -0.5 |
12 | 58 |
|
13 | 59 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 60 | + m <- x$getSolve() |
| 61 | + |
| 62 | + # check whether we got a cached calculation and return it if so |
| 63 | + if (!is.null(m)) { |
| 64 | + print("getting cached data") |
| 65 | + return(m) |
| 66 | + } else { |
| 67 | + |
| 68 | + # if we didn't have it in the cache, calculate it and store it |
| 69 | + data <- x$get() |
| 70 | + m <- solve(data) |
| 71 | + x$setSolve(m) |
| 72 | + return(m) |
| 73 | + } |
15 | 74 | }
|
0 commit comments