Skip to content

Commit f7c9199

Browse files
committed
Cached inverse of a matrix
1 parent 7f657dd commit f7c9199

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

cachematrix.R

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,37 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Set of functions show how to use <<- for setting the value of an object
2+
## that is not in current environment. Here its used as a caching mechanism
33

4-
## Write a short comment describing this function
4+
## This function returns the list of getter and setter functions
5+
## of the matrix and it's inverse
56

67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
matrixInverse <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
matrixInverse <<- NULL
12+
}
13+
get <- function() x
14+
setMatrixInverse <- function(solvedMatrixInverse) matrixInverse <<- solvedMatrixInverse
15+
getMatrixInverse <- function() matrixInverse
16+
17+
list(set = set, get = get,
18+
setMatrixInverse = setMatrixInverse,
19+
getMatrixInverse = getMatrixInverse)
820
}
921

1022

11-
## Write a short comment describing this function
23+
## Checks if the the inverse exists in the cache. If yes returns cached value
24+
## If not, calculates the inverse, set the value and then returns the same
1225

1326
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
27+
## Return a matrix that is the inverse of 'x'
28+
matrixInverse <- x$getMatrixInverse()
29+
if(is.null(matrixInverse)){
30+
#message("calculating the inverse");
31+
matrix <- x$get()
32+
inverse <- solve(matrix, ...)
33+
x$setMatrixInverse(inverse)
34+
return(inverse)
35+
}
36+
return(matrixInverse)
1537
}

0 commit comments

Comments
 (0)