|
1 |
| -## Put comments here that give an overall description of what your |
2 |
| -## functions do |
3 | 1 |
|
4 |
| -## Write a short comment describing this function |
| 2 | +## Create the capablity to cache the inverse of matrix i.e. |
| 3 | +## Compute it for first call and store it. Return the stored |
| 4 | +## for future calls |
| 5 | +## Assumption: Input matrix is invertible |
| 6 | + |
| 7 | +## Example usage: |
| 8 | +## m <- makeCacheMatrix(matrix(rep(1:4), 2,2)) |
| 9 | +## cacheSolve(m) |
| 10 | + |
| 11 | +## cacheSolve(m) will compute the inverse of the matrix for the first call and store it. |
| 12 | +## For subsequent calls, it will retrive from cache and a message will be printed denoting this behavior |
5 | 13 |
|
| 14 | +## makeCacheMatrix: Wrapper for matrix that can store inverse of a matrix |
6 | 15 | makeCacheMatrix <- function(x = matrix()) {
|
| 16 | + inverse <- NULL |
| 17 | + |
| 18 | + ##Set the value of the matrix and intialize inverse to NULL |
| 19 | + set <- function(y){ |
| 20 | + x <<- y |
| 21 | + inverse <<- NULL |
| 22 | + } |
| 23 | + |
| 24 | + ## Get the value of the matrix |
| 25 | + get <- function() x |
7 | 26 |
|
| 27 | + ## Set the value of inverse |
| 28 | + setInverse <- function(inv) inverse <<- inv |
| 29 | + |
| 30 | + ##Get the value of inverse |
| 31 | + getInverse <- function() inverse |
| 32 | + |
| 33 | + list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) |
8 | 34 | }
|
9 | 35 |
|
10 | 36 |
|
11 | 37 | ## Write a short comment describing this function
|
12 | 38 |
|
13 | 39 | cacheSolve <- function(x, ...) {
|
14 |
| - ## Return a matrix that is the inverse of 'x' |
| 40 | + ## Return a matrix that is the inverse of 'x' |
| 41 | + inverse <- x$getInverse() |
| 42 | + |
| 43 | + #Check if inverse if cached and return the cached value if it is present |
| 44 | + if(!is.null(inverse)){ |
| 45 | + message("Getting cached value for inverse") |
| 46 | + return(inverse) |
| 47 | + } |
| 48 | + |
| 49 | + #Cached inverse does not exist. Compute the inverse and store it for future calls |
| 50 | + data <- x$get() |
| 51 | + inverse = solve(data) |
| 52 | + x$setInverse(inverse) |
| 53 | + inverse |
15 | 54 | }
|
0 commit comments