|
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 |
3 | 3 |
|
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 |
5 | 6 |
|
6 | 7 | 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) |
8 | 20 | }
|
9 | 21 |
|
10 | 22 |
|
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 |
12 | 25 |
|
13 | 26 | 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) |
15 | 37 | }
|
0 commit comments