|
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 |
| - |
6 |
| -makeCacheMatrix <- function(x = matrix()) { |
| 4 | +# Special function to make an 'object' that will hold a matrix and a cached version of its inverse |
| 5 | +makeCacheMatrix <- function(m = matrix()){ |
| 6 | + matrix <- m |
| 7 | + cached_inverse <- NULL |
| 8 | + |
| 9 | + changed <- FALSE # Invariant approach to help with performance -so that the solveCache function doesn't have to track a copy of the matrix to know whether it has changed |
| 10 | + # This is fine in this scenario as there is only one function defining what the "changed" status means. |
| 11 | + |
| 12 | + #Set the matrix that this functions wraps |
| 13 | + set <- function(m) { |
| 14 | + if(!identical(matrix, m)) changed <<- TRUE |
| 15 | + matrix <<- m |
| 16 | + } |
| 17 | + |
| 18 | + #get the matrix that this function wraps |
| 19 | + get <- function() matrix |
| 20 | + |
| 21 | + #setter for cached inverse |
| 22 | + set_cached_inverse <- function(cache){ |
| 23 | + changed <<- FALSE |
| 24 | + cached_inverse <<- cache |
| 25 | + cached_inverse |
| 26 | + } |
| 27 | + #getter for cached inverse |
| 28 | + get_cached_inverse <- function(){ |
| 29 | + cached_inverse |
| 30 | + } |
| 31 | + |
| 32 | + #function to get changed status |
| 33 | + has_changed <- function() changed |
| 34 | + |
| 35 | + #function mapping |
| 36 | + list(set = set, get = get, |
| 37 | + set_cached_inverse = set_cached_inverse, |
| 38 | + get_cached_inverse = get_cached_inverse, |
| 39 | + has_changed = has_changed) |
| 40 | + |
| 41 | +} |
7 | 42 |
|
| 43 | +# Function that takes in a CacheMatrix and if not already calculated, calculates the matrix's inverse |
| 44 | +# and updating the CacheMatrix to store the new value |
| 45 | +cacheSolve <- function(cached_matrix, ...) { |
| 46 | + |
| 47 | + ## Return a matrix that is the inverse of 'cached_matrix' |
| 48 | + inverse <- cached_matrix$get_cached_inverse() |
| 49 | + |
| 50 | + #Only caclulate inverse if matrix has changed or it hasn't been calculated yet |
| 51 | + if(cached_matrix$has_changed() | |
| 52 | + is.null(cached_matrix$get_cached_inverse())){ |
| 53 | + message("Recalculating inverse") |
| 54 | + #calculate and set inverse |
| 55 | + return(cached_matrix$set_cached_inverse( |
| 56 | + solve(cached_matrix$get()) |
| 57 | + )) |
| 58 | + |
| 59 | + } |
| 60 | + inverse |
8 | 61 | }
|
9 | 62 |
|
10 |
| - |
11 |
| -## Write a short comment describing this function |
12 |
| - |
13 |
| -cacheSolve <- function(x, ...) { |
14 |
| - ## Return a matrix that is the inverse of 'x' |
15 |
| -} |
|
0 commit comments