forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
69 lines (53 loc) · 1.95 KB
/
cachematrix.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
## Put comments here that give an overall description of what your
## functions do
#makeCacheMatrix() makes a matrix object (described in more detail below) and
#cacheSolve() returns the inverse of the matrix, returning it from cache, if previously calculated.
# see more below
## Pass makeCacheMatrix() a matrix to set it as the matrix and return a list of functions.
#These functions are summarized below:
# get() returns the matrix,
# set(MatrixToSet) to set the matrix,
# setInverse(MatrixToSet) to set the cached inverse matrix,
# getInverse() returns the cached inverse matrix (which will be NULL if not set).
makeCacheMatrix <- function(storedMatrix = matrix()) {
#initialize cache matrix variable to NULL
inverseMatrix <- NULL
# set the stored matrix
set <- function(theMatrix) {
x <<- theMatrix
inverseMatrix <<- NULL
}
# get the stored matrix
get <- function() {
storedMatrix
}
# set the stored cache of the inverse matrix
setInverse <-function(inverseMatrixToSet) {
inverseMatrix <<- inverseMatrixToSet
}
# get the stored cache of the inverse matrix
getInverse <-function() {
inverseMatrix
}
# return the list of functions
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
#cacheSolve takes in the output of makeCacheMatrix(), sets the inverse
# of the stored matrix, and returns the inverse. The inverse will be cached and
# returned on future calls of the function.
cacheSolve <- function(storedMatrix, ...) {
## Return a matrix that is the inverse of the input
inverseMatrix <- storedMatrix$getInverse()
# check if inverse was previously stored- if so, return it
if(!is.null(inverseMatrix)) {
message("getting cached data")
return(inverseMatrix)
}
#otherwise compute the inverse, store it, and return it
data <- storedMatrix$get()
inverseMatrix <- solve(data)
storedMatrix$setInverse(inverseMatrix)
inverseMatrix
}