Skip to content

Commit ba0e892

Browse files
committed
implementation
1 parent 7f657dd commit ba0e892

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+
## 'cacheSolve' calculates the inverse and caches
2+
## Returns cached inverse on next call
33

4-
## Write a short comment describing this function
4+
## Stores the inverse and the matrix
5+
## Clears cached inverse, if matrix changes
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
inverse <- NULL
9+
set <- function(m) {
10+
x <<- m
11+
inverse <<- NULL
12+
}
13+
get <- function() x
14+
setInverse <- function(inverse) inverse <<- inverse
15+
getInverse <- function() inverse
16+
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
817
}
918

1019

11-
## Write a short comment describing this function
20+
21+
## If the inverse is already in cache, then returns cached
22+
## Else, calculates the inverse using solve function in R library and caches
23+
## Passes ... arguments to solve for inverse
1224

1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
inv <- x$getInverse() ## Check for cached results using getInverse
27+
if(!is.null(inv)) {
28+
message("Returning cached inverse")
29+
return(inv) ## Return cached inverse
30+
}
31+
mtx <- x$get() ## get Matrix
32+
inv <- solve(mtx, ...) ## Calculate inverse
33+
x$setInverse(inv) ## Cache calculated results
34+
inv
1535
}

0 commit comments

Comments
 (0)