Inverse of matrix with R

How and why  compute the inverse of a matrix in R?

The notion of inverse is very important in Data Analysis and in Optimisation

There are many libraries like mathlib and function to execute it : solve, ginv,inverse…

==>the standard R function for matrix inverse is solve()

1/ 2x 2 matrix

c=rbind(c(1, -1/4), c(-1/4, 1))

c
[,1]         [,2]
[1,] 1.00        -0.25
[2,] -0.25      1.00

==>det(c) is not NULL, the Inverse Matrix Exists

solve(c)
[,1]                          [,2]
[1,]  1.0666667        0.2666667
[2,] 0.2666667       1.0666667

ginv(c)
[,1]                          [,2]
[1,] 1.0666667         0.2666667
[2,] 0.2666667       1.0666667

==> you can verify , the multiplication  of c by its inverse equal I

solve(c) %*% c

if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() – t0

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() – t1

2/ 3x 3 matrix

Load the matlib package
library(matlib)

Before searching inverse ,we must verify the Determinant is not Null

Important : The ordinary inverse is defined only for square matrices.

A <- matrix( c(5, 1, 0,3,-1, 2,4, 0,-1), nrow=3, byrow=TRUE)
det(A)

## [1] 16

det(A) != 0, so inverse exists

(AI <- inv(A))

                    [,1]                 [,2]                    [,3]
## [1,] 0.0625         0.0625            0.125
## [2,] 0.6875      -0.3125            -0.625
## [3,] 0.2500       0.2500           -0.500

 

3 /Inverse of an inverse: inv(inv(A)) = A

A <- matrix(c(1, 2, 3, 2, 3, 0, 0, 1, 2), nrow=3, byrow=TRUE)
AI <- inv(A)
inv(AI)

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

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *