How to Cache a Matrix Inversion in R

Master R

This post contains my solution to one of the programming assignments from the R Programming course on coursera. If you want to solve it yourself, please don’t read any further.

When running time consuming computations, it’s good to cache the results so that you can look them up later instead of computing them again. For example, maxtrix inversion is usually costly, especially when running inside of a loop. The following functions can compute and cache the inverse of a matrix.

1. makeCacheMatrix(): creates a special “matrix” object that can cache its inverse.
2. cacheSolve(): computes the inverse of the “matrix” returned by makeCacheMatrix(). If the inverse has already been calculated and the matrix has not changed, it’ll retrieves the inverse from the cache directly.

To test out these functions. I wrote a function called test(), which takes in any invertible matrix, calculates its inverse twice using the above functions, and prints out the times it takes for both runs. The first run should take longer than the second run because it actually calculates the inverse while the second run only does a look-up from the cache.

Let’s try it on a matrix of 1000 rows and 1000 columns filled with normal random numbers.

The time it took for the first run is 2.02 seconds, and for the second run, 0.000498 seconds. This is a 99.8% decrease. Now imagine if you had to run the computation in a loop of 1000 iterations, without caching, it’s going to take you about 34 minutes, with caching, only 0.08 seconds. This is the power of caching!