Skip to content

Commit f641549

Browse files
committed
Add caching support for matrix and solve
1 parent 7f657dd commit f641549

File tree

1 file changed

+40
-9
lines changed

1 file changed

+40
-9
lines changed

cachematrix.R

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,46 @@
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-
6-
makeCacheMatrix <- function(x = matrix()) {
1+
## Cache a matrix and potentially time-consuming computations.
72

3+
## Create a caching wrapper for a matrix and potentially
4+
## time-consuming computations, including inverse (solve).
5+
makeCacheMatrix <- function(origMatrix = matrix()) {
6+
7+
## Cache
8+
cacheMatrix <- origMatrix
9+
cacheSolve <- NULL
10+
11+
## Private methods
12+
13+
# Execute solve and cache the result
14+
execSolve <- function() {
15+
cacheSolve <<- solve(cacheMatrix)
16+
}
17+
18+
## Public methods
19+
20+
# Cache a new matrix
21+
set <- function(newMatrix) {
22+
cacheMatrix <<- newMatrix
23+
cacheSolve <<- NULL
24+
}
25+
26+
# Get the cached matrix
27+
get <- function() cacheMatrix
28+
29+
# Get the cached solve
30+
getSolve <- function() {
31+
# Calculate and cache if not already cached
32+
if (is.null(cacheSolve)) execSolve()
33+
cacheSolve
34+
}
35+
36+
## Return
37+
list(set = set,
38+
get = get,
39+
getSolve = getSolve)
840
}
941

1042

11-
## Write a short comment describing this function
12-
43+
## Get the solve result of a cached matrix.
1344
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
45+
x$getSolve()
1546
}

0 commit comments

Comments
 (0)