forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
56 lines (49 loc) · 1.83 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
55
56
## Cache matrix for inverse matrix calculation
## Functions:
## makeCacheMatrix: This function creates a special "matrix" object
## that can cache its inverse.
## cacheSolve: This function computes the inverse of the special "matrix"
## returned by makeCacheMatrix above. If the inverse has already been
## calculated (and the matrix has not changed), then the cachesolve
## should retrieve the inverse from the cache
## Initialize cache inverse matrix and functions
makeCacheMatrix <- function(x = matrix()) {
# initialize the inverse matrix cache
inverse_matrix <- NULL
# define functions: set, get, setinverse, getinverse
set = function(y) {
x <<- y
inverse_matrix <<- NULL
}
get = function() x
setinverse = function(inv_matrix) inverse_matrix <<- inv_matrix
getinverse = function() inverse_matrix
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
}
## Initialize cache inverse matrix and functions
cacheSolve <- function(x, ...) {
# retrieve the cached inverse matrix
inv_matrix = x$getinverse()
# if the inverse matrix existed in the cache, use it
# otherwise calculate the inverse and store in cache
if (!is.null(inv_matrix)){
message("getting cached data")
} else {
message("calculating inverse, loading to cache")
inv_matrix <- x$setinverse(solve(x$get(),...))
}
return(inv_matrix)
}
## Test function
testCacheMatrix <- function() {
set.seed(1110201)
mat1=matrix(rnorm(10000),100,100)
temp_matrix = makeCacheMatrix(mat1)
# first time the cache should be empty, the inverse should be calculated
cacheSolve(temp_matrix)
# second time, the cache should be used
cacheSolve(temp_matrix)
# third time, the cache should be used
cacheSolve(temp_matrix)
return("Test completed")
}