How to find the inverse of a matrix in R?

R ProgrammingServer Side ProgrammingProgramming

The inverse of a matrix can be calculated in R with the help of solve function, most of the times people who don’t use R frequently mistakenly use inv function for this purpose but there is no function called inv in base R to find the inverse of a matrix.

Example

Consider the below matrices and their inverses −

> M1<-1:4
> M1<-matrix(1:4,nrow=2)
> M1
[,1] [,2]
[1,] 1   3
[2,] 2   4
> solve(M1)
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
> M2<-matrix(1:4,nrow=2,byrow=TRUE)
> M2
[,1] [,2]
[1,] 1   2
[2,] 3   4
> solve(M2)
[,1]   [,2]
[1,] -2.0 1.0
[2,] 1.5 -0.5
> M3<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34),nrow=3)
> M3
[,1] [,2] [,3] [,4]
[1,] 12  18   24   30
[2,] 14  20   26   32
[3,] 16  22   28   34
> solve(M3)
Error in solve.default(M3) : 'a' (3 x 4) must be square

Here, the function solve is giving an error because the inverse of a non-square matrix cannot be calculated.

> M4<-matrix(c(12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42),nrow=4)
> M4
[,1] [,2] [,3] [,4]
[1,] 12  20   28   36
[2,] 14  22   30   38
[3,] 16  24   32   40
[4,] 18  26   34   42
> solve(M4)
Error in solve.default(M4) :
Lapack routine dgesv: system is exactly singular: U[3,3] = 0

This output is showing an error because the inverse of the matrix M4 does not exists, although it is a square matrix but sometimes even the inverse of a square does not exist.

Let’s have a look at some matrices with higher dimensions that have their inverses −

> M5<-matrix(c(1,8,4,2,4,5,5,1,2,2,5,4,4,1,1,2),nrow=4)
> M5
[,1] [,2] [,3] [,4]
[1,] 1   4    2    4
[2,] 8   5    2    1
[3,] 4   5    5    1
[4,] 2   1    4    2
> solve(M5)
[,1]          [,2]        [,3]     [,4]
[1,] -0.07086614  0.17322835 -0.1417323  0.1259843
[2,]  0.11023622 -0.04724409  0.2204724 -0.3070866
[3,] -0.09448819 -0.10236220  0.1443570  0.1679790
[4,]  0.20472441  0.05511811 -0.2572178  0.1916010
> M6<-matrix(c(2,3,5,4,7,4,5,6,5,2,1,4,5,6,6,2,5,5,4,5,4,7,5,7,3),ncol=5)
> M6
[,1] [,2] [,3] [,4] [,5]
[1,] 2   4     1    2    4
[2,] 3   5     4    5    7
[3,] 5   6     5    5    5
[4,] 4   5     6    4    7
[5,] 7   2     6    5    3
> solve(M6)
[,1]         [,2]       [,3]        [,4]        [,5]
[1,]  5.000000e-01 -0.24000000 -0.2200000  1.194481e-16  0.260000000
[2,]  1.457168e-16 -0.20000000  0.4000000 -8.500145e-17 -0.200000000
[3,] -4.285714e-01 -0.12571429  0.1942857  2.857143e-01 -0.125714286
[4,] -3.571429e-01  0.50857143  0.1685714 -4.285714e-01  0.008571429
[5,]  2.857143e-01  0.09714286 -0.4228571  1.428571e-01  0.097142857
Published on 10-Aug-2020 12:08:49