forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
56 lines (44 loc) · 1.38 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
46
47
48
49
50
51
52
53
54
# makeCacheMatrix is the function that can be used to cache the results of a calculation on a matrix
# the results are stored in the 'm'variable in the environment of the function
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setsolve <- function(abc) m <<- abc
getsolve <- function() m
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
##################################################################
#cacheSolve is a function that calculates the inverse matrix of a given input.
#whenever the result of the calculation is alerady available in cache, it returns that.
# if it is not, it wil calculate the icerse matrix and return the result.
cacheSolve <- function(x, ...)
{
## Return a matrix that is the inverse of 'x'
m <- x$getsolve()
if(!is.null(m)) {
message("getting cached data")
#return(m)
m
}
data <- x$get()
m <- solve(data, ...)
x$setsolve(m)
m
}
###################################################################
# for testing purposes:
# define the matrix
ma<- matrix(rnorm(16),4,4)
ma
# execute the MakeCacheMatrix function to put the ma patrix into a.
a<-makeCacheMatrix(ma)
# execute cacheSolve a first time (not chached)
cacheSolve(a)
# execute cacheSolve second time, not the result comes from cahce
cacheSolve(a)