In: Statistics and Probability
From the R,
When I try to the qr.solve(crossprod(X.matrix)), it said "Error in qr.solve(crossprod(X.matrix)) : singular matrix 'a' in solve."
How to solve it this error?
The error may be due to the following reasons:
1- X.matrix is a singular matrix.
Singular Matrix: A square matrix is singular if and only if its determinant is 0.
2- crossprod() function gives us the singular matrix when operated on X.matrix.
To resolve this you have to check that whether X.matrix is singular or not.
You can use solve() command to check whether the matrix is singular or not.
solve() command will show following error if the matrix is singular.
Error in solve.default(X.matrix) :
Lapack routine dgesv: system is exactly singular: U[3,3] =
0
You can also verify it using det() command in R. which will give you the determinant of matrix. If the determinant is 0; It means that matrix is singular.
Try following commands
det(X.matrix)
det(crossprod(X.matrix))
solve(X.matrix)
slove(crossprod(X.matrix))
If the matrix is singular try to make it non-singular. Check for other errors in the program.
Below is the code for qr.solve in R.
function (a, b, tol = 1e-07)
{
if (!inherits(a, "qr"))
a <- qr(a, tol = tol)
nc <- ncol(a$qr)
nr <- nrow(a$qr)
if (a$rank != min(nc, nr))
stop("singular matrix 'a' in solve")
if (missing(b)) {
if (nc != nr)
stop("only square matrices can be inverted")
b <- diag(1, nc)
}
res <- qr.coef(a, b)
res[is.na(res)] <- 0
res
}
See the bold part in the code. It is using Rank method of matrix to check whether a matrix is singular or not. Inverse of a singular matrix does not exist.