How to check if a matrix has an inverse in R

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

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

"TRUE" (this matrix has the opposite side) / "FALSE" (it does not ...).

+6
source share
4 answers

@MAB has a good point. To do this, use solve(...) to decide if the matrix is ​​invertible.

 f <- function(m) class(try(solve(m),silent=T))=="matrix" x <- matrix(rep(1,25),nc=5) # singular y <- matrix(1+1e-10*rnorm(25),nc=5) # very nearly singular matrix z <- 0.001*diag(1,5) # non-singular, but very smalll determinant f(x) # [1] FALSE f(y) # [1] TRUE f(z) # [1] TRUE 
+3
source

Using abs(det(M)) > threshold as a way to determine matrix invertibility is a very bad idea. Here is an example: consider the class of matrices cI, where I am the identity matrix and c is a constant. If c = 0.01 and I am 10 × 10, then det (cI) = 10 ^ -20, but (cI) ^ - 1 most definitely exists and just 100I. If c is small enough, det() will overflow and return 0, even if the matrix is ​​invertible. If you want to use determinants to check for reversibility, check if the module of the logarithmic determinant is finite using determinant() .

+8
source

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

To install the package:

 install.packages("matrixcalc") 

To download it:

 library(matrixcalc) 

To create a matrix:

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

To check this:

 is.singular.matrix(mymatrix) 

If the matrix is ​​invertible, it returns FALSE , and if the matrix is ​​synchronous / irreversible, it returns TRUE .

+6
source

In addition to the solution given by @josilber in the comments (i.e. abs(det(M)) > 1e-10 ), you can also use solve(M) %*% M for the square matrix or ginv in the MASS package, will give generalized inverse matrix symbol.

To get TRUE or FALSE , you can simply combine any of these methods with tryCatch and any as follows:

out <- tryCatch(solve(X) %*% X, error = function(e) e)

any(class(out) == "error")

+1
source

Source: https://habr.com/ru/post/972850/


All Articles