Skip to content

Commit 04f1495

Browse files
committed
Implement makeCacheMatrix() and cacheSolve()
1 parent 7f657dd commit 04f1495

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

cachematrix.R

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,35 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Avoid repetetive calculations of inverse of a matrix by caching the inverse
32

4-
## Write a short comment describing this function
3+
## Create a special "matrix" object that can cache its inverse
54

65
makeCacheMatrix <- function(x = matrix()) {
7-
6+
inv <- NULL
7+
set <- function(y) {
8+
x <<- y
9+
inv <<- NULL # Invalidate the cache due to change of matrix
10+
}
11+
get <- function() x
12+
setInv <- function(invM) inv <<- invM
13+
getInv <- function() inv
14+
15+
list(set = set, get = get,
16+
setInv = setInv,
17+
getInv = getInv)
818
}
919

1020

11-
## Write a short comment describing this function
21+
## Return a matrix that is the inverse of "x".
22+
## Use cached result when available, otherwise first calculate the reverse and update the cache.
23+
## "x" is a "matrix" object created by makeCacheMatrix()
1224

1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
inv <- x$getInv()
27+
if(!is.null(inv)) {
28+
message("Getting cached data")
29+
return(inv)
30+
}
31+
data <- x$get()
32+
inv <- solve(data, ...)
33+
x$setInv(inv)
34+
inv
1535
}

0 commit comments

Comments
 (0)