forked from rdpeng/ProgrammingAssignment2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcachematrix.R
More file actions
53 lines (40 loc) · 1.23 KB
/
cachematrix.R
File metadata and controls
53 lines (40 loc) · 1.23 KB
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
## Put comments here that give an overall description of what your
## functions do
# The function returns a new CacheMatrix object, which is a list
# that contains functions to access the matrix and its cached inverse form
makeCacheMatrix <- function(x = matrix()) {
s <- NULL
set <- function(y) {
x <<- y
r <<- NULL
}
get <- function() x
setsolve <- function(computed_solve) s <<- computed_solve
getsolve <- function() s
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
# The function returns a cached inverse matrix of a CacheMatrix object
# If the cached data is not present, it is computed and saved
cacheSolve <- function(x, ...) {
s <- x$getsolve()
if(!is.null(s)) {
message("getting cached data")
return(s)
}
data <- x$get()
s <- solve(data, ...)
x$setsolve(s)
s
}
# Simple function to test the implementation
testCacheMatrix <- function() {
m <- matrix(c(1:4),2,2)
cm <- makeCacheMatrix(m)
# Iteration 1: value is calculated, Iteration 2&3: cached value returned
for (i in 1:3) {
print(paste0("Iteration ", i))
print(cacheSolve(cm))
}
}