forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
41 lines (32 loc) · 1.32 KB
/
Copy pathcachematrix.R
File metadata and controls
41 lines (32 loc) · 1.32 KB
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
## These functions allow for caching the inverse of a given matrix so that the inverse can be retrieved later
## without the need to recalculate
## Creates "matrix" object that is a list of functions for storing/modifying a given matrix's inverse
makeCacheMatrix <- function(x = matrix()) {
##initialize inverse to NULL as it has not been calculated yet
inv <- NULL
##create set/get functions for the given matrix and its inverse and generate a list that serves as the cache
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInv <- function(inverse) inv <<- inverse
getInv <- function() inv
list (set = set, get = get, setInv = setInv, getInv = getInv)
}
## Given a "matrix" object generated by makeCacheMatrix, this function obtains the cached inverse or calculates the inverse
## using solve() and caches it in the "matrix" object for future use
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
## return cached value if it exists, i.e., inv is not null
inv <- x$getInv()
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}
## otherwise, calculate the inverse now and cache it
data <- x$get()
inv <- solve(data, ...)
x$setInv(inv)
inv
}