Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ba3fa75

Browse files
committed
Update cachematrix.R
1 parent 7f657dd commit ba3fa75

File tree

1 file changed

+62
-9
lines changed

1 file changed

+62
-9
lines changed

cachematrix.R

Lines changed: 62 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,68 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
5-
1+
## Creates a special "matrix" object that can cache its inverse.
62
makeCacheMatrix <- function(x = matrix()) {
3+
inv <- NULL # cached inverse
4+
5+
# mutator for the encapsulated matrix - also resets cached result to NULL
6+
set <- function(y) {
7+
# only reset inverse if matrix are not equal
8+
if ( !(all(dim(x) == dim(y)) && all(x==y)) ) { inv <<- NULL }
79

10+
# set encapsulated matrix in all cases
11+
x <<- y
12+
}
13+
14+
# accessor - return encapsulated matrix
15+
get <- function() { x }
16+
17+
# mutator for the inverse matrix
18+
set_inv <- function(inv_new) { inv <<- inv_new }
19+
20+
# accessor for the inverse matrix
21+
get_inv <- function() { inv }
22+
23+
# wrap everything into a list
24+
list(set = set, get = get, set_inv = set_inv, get_inv = get_inv)
825
}
926

10-
11-
## Write a short comment describing this function
12-
27+
## Computes the inverse of the special "matrix" returned by makeCacheMatrix().
28+
## The inverse is computed only once. Cache results are used in subsequent calls.
1329
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
30+
## Return a matrix that is the inverse of 'x'
31+
32+
# return any non-NULL cached result
33+
inv <- x$get_inv()
34+
if(!is.null(inv)) { return(inv) }
35+
36+
# no cached result exists - calculate it and return
37+
realmtx <- x$get()
38+
inv <- solve(realmtx, ...)
39+
x$set_inv(inv)
40+
return(inv)
1541
}
42+
43+
## This function implements a loop for demonstrating the speed gains
44+
## from caching the matrix inverse.
45+
timeloop <- function(x, usecache=FALSE, n=1) {
46+
if (usecache) {
47+
message("Loop using cached inverse...")
48+
xc <- makeCacheMatrix(x)
49+
for(i in 1:n) {
50+
inv <- cacheSolve(xc)
51+
}
52+
}
53+
else {
54+
message("Loop without cached inverse...")
55+
xc <- x
56+
for(i in 1:n) {
57+
inv <- solve(xc)
58+
}
59+
}
60+
message("Done.")
61+
print(inv)
62+
message()
63+
}
64+
65+
## Run the timing loop with caching disabled/enabled.
66+
mtx <- matrix(c(3,1,2,1,1,1,2,1,1), nrow=3, ncol=3)
67+
print(system.time(timeloop(mtx, usecache=FALSE, n=80000)))
68+
print(system.time(timeloop(mtx, usecache=TRUE, n=80000)))

0 commit comments

Comments
 (0)