Skip to content

Commit 230cf84

Browse files
committed
Complete assignment 2
1 parent 7f657dd commit 230cf84

File tree

1 file changed

+56
-9
lines changed

1 file changed

+56
-9
lines changed

cachematrix.R

Lines changed: 56 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,62 @@
11
## Put comments here that give an overall description of what your
22
## functions do
33

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+
}
742

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
861
}
962

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

Comments
 (0)