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
90 lines (71 loc) · 2.11 KB
/
cachematrix.R
File metadata and controls
90 lines (71 loc) · 2.11 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
## Owen Patrick - rprog-014
## makeCacheMatrix is an object that holds a matrix and the
## cached results of its inverse matrix and determinant. The
## function cacheSolve checks, computes and writes the
## results of the determinant and inverse to the
## makeCacheMatrix object passed in.
## func: makeCacheMatrix
## Takes in a square matrix and constructs a class
## wrapper to store the cached result of its Determinant and
## Inverse, if the Inverse exists. Otherwise, it stores the
## Determinant and the value "NA" for the Inverse.
makeCacheMatrix <- function(x = matrix()) {
if(!is.matrix(x)) { message("Parameter is not a matrix."); return(NULL) }
if(!is.atomic(x)) { message("Parameter is atomic."); return(NULL) }
if((ncol(x) != nrow(x))) { message("Matrix is not square."); return(NULL) }
result <- NULL
dtmnt <- NULL
set <- function(y) { ## y here is the incoming matrix
x <<- y
result <<- NULL
dtmnt <<- NULL
}
get <- function() {
x
}
setInverse <- function(inverseData) {
result <<- inverseData
}
getInverse <- function() {
result
}
setDet <- function(detData) {
dtmnt <<- detData
}
getDet <- function() {
dtmnt
}
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse,
setDet = setDet,
getDet = getDet)
}
## func: cacheSolve
## Takes in an instance of makeCacheMatrix and does the following:
## 1. Checks the determinant of the matrix in makeCacheMatrix class.
## 2. If the determinant is not null, fetch the inverse result.
## 3. If it is null, compute and store it and then compute and store
## the Inverse Matrix; NA if the determinant is 0.
cacheSolve <- function(x, ...) {
result <- x$getDet()
if(!is.null(result)) {
message("getting cached data")
return(x$getInverse())
}
data <- x$get()
dtrmnt <- determinant(data)$modulus[1]
x$setDet(dtrmnt)
if(is.infinite(dtrmnt)) {
message("System is computationally singular OR exactly singular")
x$setInverse(NA)
return(NA)
}
result <- tryCatch(solve(data, ...), error= function(err) {
message(err)
x$setInverse(NA)
return(NA)
})
x$setInverse(result)
result
}