forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
45 lines (35 loc) · 1.58 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
## Doing Matrix Inversion calculation could take time.
## Caching the result of an inversion on a matrix will greatly
## improve the performance of the program is the inversion
## is reused more than once.
##
## The following functions cache the result of applying solve()
## on a matrix. If m is matrix, solve(m) returns the inversion of m
##---------------------------------------------------------------------##
## Create a matrix with setters, getters and cached result for solve()
makeCacheMatrix <- function(x = matrix()) {
sol <- NULL
set <- function(y) {x <<- y ; sol <<- NULL}
get <- function() x
setSol <- function(newSol) sol <<- newSol
getSol <- function() sol
list(set = set, get = get, setSol = setSol, getSol = getSol)
}
##---------------------------------------------------------------------##
## Retrive and assign cached value according to the presence of the cache
cacheSolve <- function(x, ...) {
if(is.null(x$getSol()))
x$setSol( solve(x$get(), ...) )
else
message("getting cached data")
x$getSol()
}
##---------------------------------------------------------------------##
##---------------------------------------------------------------------##
## Uncomment the next 4 lines of code to test the above functions
## (Hightlight the lines then use Ctrl-Shift-C to uncomment)
# m<-makeCacheMatrix(matrix(1:4,2,2))
# cacheSolve(m) # This call tests solve(a)
# cacheSolve(m) # This call tests caching
# m$set(matrix(c(1,2,3,6,5,4,9,7,8),3,3,byrow=T))
# cacheSolve(m,m$get()) # This call tests solve(b,b)