Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than compute it repeatedly. Below is a pair of functions that cache the inverse of a matrix.

Function 1

Function named makeCacheMatrix creates a special “matrix” object that can cache its inverse. This function creates a list object from the input matrix containing functions to 1 set the value of the matrix 2 get the value of the matrix 3 set the value of the inverse 4 get the value of the inverse

makeCacheMatrix <- function(x = matrix()) {
    inv <- NULL
    set <- function(y) {
        x <<- y
        inv <<- NULL
    }
    get <- function() x
    setinv <- function(inverse) inv <<- inverse
    getinv <- function() inv
    list(set = set, get = get,
         setinv = setinv,
         getinv = getinv)
}

Function 2

Function named cacheSolve computes the inverse of the special “matrix” returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cachesolve retrieves the inverse from the cache. Computing the inverse of a square matrix can be done with the solve function in R.

cacheSolve <- function(x, ...) {
    inv <- x$getinv()
    if(!is.null(inv)) {
        message("getting cached data")
        return(inv)
    }
    data <- x$get()
    inv <- solve(data, ...)
    x$setinv(inv)
    inv
}

Testing

Create a matrix:

tridiag <- function(upper, lower, main){
    out <- matrix(0,length(main),length(main))
    diag(out) <- main
    indx <- seq.int(length(upper))
    out[cbind(indx+1,indx)] <- lower
    out[cbind(indx,indx+1)] <- upper
    return(out)
}

h <- tridiag(rep(1,999),rep(1,999),rep(2,1000))
hc <- makeCacheMatrix(h)

First call:

system.time(cacheSolve(hc))
##    user  system elapsed 
##   2.534   0.039   2.603

Second call:

system.time(cacheSolve(hc))
## getting cached data
##    user  system elapsed 
##   0.001   0.000   0.000