forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcachematrix.R
34 lines (30 loc) · 1.09 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
# MakeCacheMatrix is used to create a Cachable Matrix, it accepts an R matrix as input.
# our representation is a set list of four functions, used to set/get the matrix,
# and get/set the cached answer.
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setsolve <- function(solve) m <<- solve
getsolve <- function() m
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
#cacheSolve accepts a cacheableMatrix generated by "makeCacheMatrix", it expects the representation
# to be a list of four functions (see makeCacheMatrix)
cacheSolve <- function(x, ...) {
m <- x$getsolve() # check for a cached answer
if(!is.null(m)) { # cached data exist
message("getting cached data")
return(m)
}
# if we are here, means we didn't find it in cache, need to create it and store it
data <- x$get() # retreive stored matrix
m <- solve(data, ...) # use R's solve to solve the matrix
x$setsolve(m) # store the result in cache, will be available next time
m
}