# 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

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)

##  16

det(A) != 0, so inverse exists

(AI <- inv(A))

# 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