Skip to content

Commit 58a6083

Browse files
author
Keyur Gabani
committed
Implement makeCacheMatrix and cacheSolve
1 parent 7f657dd commit 58a6083

File tree

1 file changed

+43
-4
lines changed

1 file changed

+43
-4
lines changed

cachematrix.R

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,54 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
31

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
513

14+
## makeCacheMatrix: Wrapper for matrix that can store inverse of a matrix
615
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
726

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)
834
}
935

1036

1137
## Write a short comment describing this function
1238

1339
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
1554
}

0 commit comments

Comments
 (0)