Skip to content

Commit 4d7bcb9

Browse files
committed
added makeCacheMatrix and cacheSolve functions
1 parent 7f657dd commit 4d7bcb9

File tree

1 file changed

+44
-4
lines changed

1 file changed

+44
-4
lines changed

cachematrix.R

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,54 @@
22
## functions do
33

44
## Write a short comment describing this function
5-
6-
makeCacheMatrix <- function(x = matrix()) {
5+
# creates a list to encapsulate a matrix with various helper functions for that matrix, particularly a caching mechanism
6+
# logic for the caching is not included here, this function only creates the data structure that will be used by separate
7+
# caching logic.
8+
# helper functions include:
9+
# getInverse: returns the matrix inverse (computation is cached automatically, no need to set the value manually...)
10+
# get and set: getting and setting the matrix object (setting clears the cached inverse)
11+
# makeCacheMatrix ssumes the matrix is always invertible
12+
makeCacheMatrix <- function(subjectMatrix = matrix()) {
13+
inverse <- NULL
14+
set <- function(newMatrix) {
15+
subjectMatrix <<- newMatrix
16+
inverse <<- NULL
17+
}
18+
19+
get <- function() {
20+
subjectMatrix
21+
}
22+
23+
getInverse <- function() {
24+
inverse
25+
}
26+
27+
setInverse <- function(newInverse) {
28+
inverse <<- newInverse
29+
}
30+
31+
# assign a reference to the function to the label of the same name
32+
list(set = set, get = get, getInverse = getInverse, setInverse = setInverse)
733

834
}
935

1036

1137
## Write a short comment describing this function
12-
38+
# a caching wrapper for the solve() command when being used to calculate the matrix inverse.
39+
# to be used in conjunction with makeCacheMatrix, expects a data structure defined by makeCacheMatrix()
1340
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
41+
## Return a matrix that is the inverse of 'x'
42+
43+
if (is.null(x$getInverse())) {
44+
# compute and cache the matrix inverse
45+
message("cachematrix: cache empty, calculating inverse with solve()")
46+
x$setInverse(solve(x$get(), ...))
47+
} else {
48+
#report that we're using a cached value
49+
message("cachematrix: using cached value")
50+
}
51+
52+
# return the cached inverse
53+
x$getInverse()
54+
1555
}

0 commit comments

Comments
 (0)