Skip to content

Commit 3c4815c

Browse files
committed
implement matrix caching
1 parent 7f657dd commit 3c4815c

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

cachematrix.R

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,27 @@
44
## Write a short comment describing this function
55

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
cachedInverse <- NULL
8+
getMatrix <- function () x
9+
inverse <- function () cacheSolve(x)
10+
getInverse <- function () cachedInverse
11+
setInverse <- function (i) cachedInverse <<- i
12+
13+
list(getMatrix = getMatrix, inverse = inverse, setInverse = setInverse, getInverse = getInverse)
814
}
915

1016

1117
## Write a short comment describing this function
1218

1319
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
20+
if (is.null(x$getInverse())) {
21+
x$setInverse(solve(x$getMatrix(), ...))
22+
}
23+
24+
x$getInverse()
1525
}
26+
27+
# test:
28+
# hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
29+
# h8 <- hilbert(8)
30+
# cm <- makeCacheMatrix(h8)

0 commit comments

Comments
 (0)