forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
53 lines (43 loc) · 1.24 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
# makeCacheMatrix creates a list containing a function to
# 1. set the value of the matrix
# 2. get the value of the matrix
# 3. set the value of inverse of the matrix
# 4. get the value of inverse of the matrix
makeCacheMatrix <- function(x = numeric()) {
# holds the cached value or NULL if nothing is cached
# initially nothing is cached so set it to NULL
cache <- NULL
# store a matrix
setMatrix <- function(newValue) {
x <<- newValue
# since the matrix is assigned a new value, flush the cache
cache <<- NULL
}
# returns the stored matrix
getMatrix <- function() {
x
}
# cache the given argument
cacheInverse <- function(solve) {
cache <<- solve
}
# get the cached value
getInverse <- function() {
cache
}
# return a list. Each named element of the list is a function
list(setMatrix = setMatrix, getMatrix = getMatrix, cacheInverse = cacheInverse, getInverse = getInverse)
}
## Calculate the inverse of the special "matrix" created with the above
## function, reusing cached result if it is available
cacheSolve <- function(x, ...) {
i <- x$getinverse()
if(!is.null(i)) {
message("getting cached data")
return(i)
}
m <- x$get()
i <- solve(m, ...)
x$setinverse(i)
i
}