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
60 lines (46 loc) · 2.1 KB
/
cachematrix.R
File metadata and controls
60 lines (46 loc) · 2.1 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
## The first function makes a list with methods that set and get a matrix and its inverse in an intrinsic environment variable
## The second function is passed the list from the first and attempts to calculate and set its inverse. If the inverse is already set, teh cached value is used
## makeCacheMatrix will create a matrix x, and expose three methods to set/get x and its inverse
makeCacheMatrix <- function(x = matrix()) {
## initialize inverse
cachedInv <- NULL
## set x in parent env with the desired value, if inverse is already set, get rid of it!
set <- function(userValue = matrix()) {
x <<- userValue
cachedInv <<- NULL
}
get <- function() x
##set inverse variable in parent env to desired value and return the value as a convenience
setInverse <- function(invVal) {
cachedInv <<- invVal
return(cachedInv)
}
getInverse <- function() cachedInv
list(set=set, get=get, setInverse=setInverse, getInverse=getInverse)
}
## Given the list variable from the first function, will first check to see if there's already a cached inverse and return
cacheSolve <- function(x=makeCacheMatrix(1:4, nrow=2, ncol=2), ...) {
## Checking exist
calculatedInverse <- x$getInverse()
##check if there's a cached value AND it's a matrix
if(!is.null(calculatedInverse) && is.matrix(calculatedInverse)) {
message("We found cached data and saved valuable cpus!!!")
return(calculatedInverse)
}
## otherwise get the matrix
matrixToSolve <- x$get()
## try to solve the matrix and catch errors and warnings
calculatedInverse <- tryCatch({
solve(matrixToSolve)
}, warning=function(w) {
message("This may not be the result you're looking for")
message(w)
}, error=function(e) {
message("Something went wrong solving your matrix")
message(e)
message("\n")
})
## whatever the case, set the value of the inverse (NULL if something went wrong)
message("Setting the value of inverse to:")
x$setInverse(calculatedInverse)
}