Skip to content

Commit 752150b

Browse files
committed
implement cache solve and cachematrix
1 parent 7f657dd commit 752150b

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

cachematrix.R

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

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
cached.result <- NULL
8+
set <- function(y) {
9+
x <<- y
10+
cached.result <<- NULL
11+
}
12+
get <- function() x
13+
set.cached.result <- function(result) cached.result <<- result
14+
get.cached.result <- function() cached.result
15+
list(set = set, get = get,
16+
set.cached.result = set.cached.result,
17+
get.cached.result = get.cached.result)
818
}
919

1020

1121
## Write a short comment describing this function
1222

13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
23+
cacheSolve <- function(matrix, ...) {
24+
res <- matrix$get.cached.result()
25+
if(!is.null(res)) {
26+
message("getting cached data")
27+
return(res)
28+
}
29+
data <- matrix$get()
30+
res <- solve(data)
31+
matrix$set.cached.result(res)
32+
res
1533
}
34+
35+
#example of invertible matrix
36+
# hilbert <- function(n) { i <- 1:n; 1 / outer(i - 1, i, "+") }
37+
# h8 <- hilbert(8)

0 commit comments

Comments
 (0)