DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Caching an Inverse of a Matrix UsingΒ R
Masteramuk
Masteramuk

Posted on

Caching an Inverse of a Matrix UsingΒ R

Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than computing it repeatedly.

This is an example code to cache an inverse of a matrix which then called if:

  1. The new matrix computation similar to the previous matrix
  2. Matrix is invertibleβ€Šβ€”β€ŠRead Invertible Matrix
  3. The structure and content of the new matrix is equal to previous The program consists of two functions

A function to cache the matrix and the inverse. It is similar to getter and setter in many programming languages like Java and C.
A function which will be call for the computational process of the matrix

Here are parts of the code:

Setting the matrix

invMatrix <- NULL

#define the set function for the matrix
set <- function(y) {
    x <<- y
    invMatrix <<- NULL
}

Setting the inverse matrix

setInvMatrix <- function(invM){
    invMatrix <<- invM ##assign the inverse matrix to the environment var
} 

##define the function for returning the inverse matrix
getInvMatrix <- function(){
    invMatrix ##the environment var inverse matrix is return
}

Verification on the matrix

if (!is.null(invM)){
    ## check if the return invMatrix is identical
    if ( identical( x$get() %*% invM, invM %*% x$get() ) ){
        ## get it from the cache and skips the computation. 
        print("getting cached data")
        return(invM)
    }
}

Setting the new inverse

data <- x$get()
invM <- solve(data, ...)

# sets the value of the inverse in the cache via the setinv function.
x$setInvMatrix(invM)

Complete source code is reachable at https://github.com/masteramuk/ProgrammingAssignment2

If you like the post, https://www.buymeacoffee.com/masteramuk :)

Top comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: