I wrote this R function which caches the Inverse of a matrix in memory to avoid recalculation when the inverse is requested for the same matrix again or calculate a new inverse if the matrix changes and caches the result in memory. Below is the code and can be copied and tested in R.
##Function creates a special “matrix” and provides function to set values,get ##values,set inverse, get inverse
makeCacheMatrix <- function(x = matrix()) {
I <- NULL
set <- function(y) {
x <<- y
I <<- NULL
}
get <- function() x
setInverse <- function(solve) {
I <<- solve
## store the matrix that resulted in getting inverse
## so we can compare next time for equality if we can reuse old inverse or ##recalculate
stored <<- x
}
getInverse <- function() I
getStored <- function() stored
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse,
getStored = getStored)

}

## Below  Function will look into cache to see if inverse exist for matrix and ##retrieve the value. if its the same matrix but will calculate if no inverse exist or ##matrix is not same.
cacheSolve <- function(x=matrix(), …) {
## Return a matrix that is the inverse of ‘x’
I <- x$getInverse()
if(!is.null(I)){
##check to see if nrow and ncol for new matrix is same as the one stored whose ##inverse is cached
if((nrow(x$getStored()) == nrow(x$get())) && (ncol(x$getStored()) == ncol(x$get())))
{
##check to see if the new matrix is identical to stored one
##after they are found to have same nrow and ncol
if(identical(x$getStored(),x$get())){
message(“getting cached data”)
return(I)
}
}
}
data <- x$get()
I <- solve(data)
x$setInverse(I)
I
}

This is how to use the function.

mymatrix <- makeCacheMatrix(c(1:4),nrow=2,ncol=2)

cacheSolve(mymatrix)

output:

[,1]          [,2]
[1,]   -2            1.5
[2,]    1           -0.5

The outcome is the inverse and this will be cached in memory but a new inverse will get calculated when a different matrix is submitted.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *