How to compute inverse of a matrix in R

In this tutorial, we will show how to compute inverse of matrix in R. Computing inverse of a matrix is core to multiple applications.

In linear algebra, inverse of a matrix is defined as a matrix that, when multiplied by the original matrix, results in the identity matrix. In other words, if A is a square matrix and A^-1 is its inverse, then A*A^-1 = I, where I is the identity matrix.

In R, we can use solve() function to find the inverse of a matrix.

The basic syntax is as follows

solve(A)

where A is the matrix for which we want to find the inverse.

Let us see an example of computing inverse of a 3×3 matrix in R using solve() function.

A <- matrix(c(1,2,9,4,5,6,7,8,9),
            nrow = 3,
            byrow=TRUE)

Our 3 x 3 matrix looks like this.

A

##      [,1] [,2] [,3]
## [1,]    1    2    9
## [2,]    4    5    6
## [3,]    7    8    9

We can use solve() function to compute the inverse.

A_inverse <- solve(A)

And the inverse of the matrix looks like this.

A_inverse

##            [,1]       [,2]       [,3]
## [1,]  0.1666667 -3.0000000  1.8333333
## [2,] -0.3333333  3.0000000 -1.6666667
## [3,]  0.1666667 -0.3333333  0.1666667

We can verify if this is the inverse of the input matrix, by multiplying the inversee with the original matrix. And we should get unit matrix with ones along the diagonal and zeros else where.

When we do matrix multiplication with %*% symbol we get the following matrix that looks like a unit matrix.

A %*% A_inverse

##              [,1]         [,2]          [,3]
## [1,] 1.000000e+00 0.000000e+00  0.000000e+00
## [2,] 2.220446e-16 1.000000e+00 -5.551115e-16
## [3,] 0.000000e+00 1.332268e-15  1.000000e+00

Wee can further make sure if thee result is a unit matrix by rounding it.

round(A %*% A_inverse)

##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1

Thee order of multiplication of inverse of matrix and original matrix does not matter. Here we get unit matrix by changing the order of multiplication.

A_inverse %*% A


##              [,1]          [,2]          [,3]
## [1,] 1.000000e+00 -3.552714e-15 -3.552714e-15
## [2,] 1.776357e-15  1.000000e+00  3.552714e-15
## [3,] 0.000000e+00 -2.220446e-16  1.000000e+00

It’s important to note that not all matrices have inverses. A matrix can only have an inverse if it is non-singular, meaning that its determinant is non-zero. In R, the det() function can be used to find the determinant of a matrix.

Exit mobile version