Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a matrix has an inverse in the R language

How do you determine if a matrix has an inverse in R?

So is there in R a function that with a matrix input, will return somethin like:

"TRUE" (this matrix has inverse)/"FALSE"(it hasn't ...).

like image 206
hamsternik Avatar asked Jul 25 '14 18:07

hamsternik


2 Answers

You can try using is.singular.matrix function from matrixcalc package.

To install package:

install.packages("matrixcalc")

To load it:

library(matrixcalc)

To create a matrix:

mymatrix<-matrix(rnorm(4),2,2)

To test it:

is.singular.matrix(mymatrix)

If matrix is invertible it returns FALSE, and if matrix is singlar/non-invertible it returns TRUE.

like image 127
Akki Avatar answered Oct 03 '22 11:10

Akki


Using abs(det(M)) > threshold as a way of determining if a matrix is invertible is a very bad idea. Here's an example: consider the class of matrices cI, where I is the identity matrix and c is a constant. If c = 0.01 and I is 10 x 10, then det(cI) = 10^-20, but (cI)^-1 most definitely exists and is simply 100I. If c is small enough, det() will underflow and return 0 even though the matrix is invertible. If you want to use determinants to check invertibility, check instead if the modulus of the log determinant is finite using determinant().

like image 37
MAB Avatar answered Oct 03 '22 10:10

MAB