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 (49 loc) · 1.62 KB
/
Copy pathcachematrix.R
File metadata and controls
60 lines (49 loc) · 1.62 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
library(MASS)
## creates a list object that contains functions to set or retrieve information about the matrix to be inverted and the inverted matrix if it has been calculated
## NOTE: setmatr should not be used outside the bounds of cacheSolve
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y){
x <<- y
m <<- NULL
}
get <- function() x
setmatr <- function(res) m <<- res
getmatr <- function() m
list(set = set, get = get,
setmatr = setmatr,
getmatr = getmatr)
}
## A function to check for the presence of a calculated solution and to obtain a solution if no solution is present. Solution is obtained via Gauss-Jordan Elimination (GJE)
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getmatr()
if (!is.null(m)){
message("getting cached data")
return(m)
}
res <- x$get()
## calculate inverse
## prepping identity matrix for GJE
size <- length(res[1,])
I <- matrix(0, size, size)
I[col(I)==row(I)] <- 1
res <- cbind(res,I)
## executing GJE
for(i in 1:(size-1)){
res[i,] <- res[i,] / res[i,i]
for(j in (i+1):size){
res[j,] <- res[j,] - (res[j,i]/res[i,i])*res[i,]
}
}
res[size,] <- res[size,] / res[size,size]
for(i in size:2){
for(j in (i-1):1){
res[j,] <- res[j,] - (res[j,i]/res[i,i])*res[i,]
}
}
##extracting resultant matrix
m <- fractions(res[,(size+1):(2*size)])
fractions(x$setmatr(m))
m
}