-1

R 0.99.893 solve() on Windows 10 - Error in solve.default(a)

Trying to calculate the inverse of a square matrix, but getting an error:

a <- matrix(1:16, 4,4) solve(a) Error in solve.default(a) : Lapack routine dgesv: system is exactly singular: U[3,3] = 0

I also tried solve(a, diag(4)) but got the same error.

  • 2
    It's a good idea to Google such error messages before posting questions. Doing so would have led you directly to duplicate questions, like the one referenced above. – nrussell May 31 '16 at 15:38
  • 1
    R version 0.99.893? That must be more than 15 years old. We are now on version 3.3.0. You should consider updating. (R studio and R are distinct pieces of software). – lmo May 31 '16 at 16:08
  • @ZheyuanLi It is pretty frustrating that people conflate the two pieces of software as one predates the other by at least 10 years. (and, technically, the latest version is 0.99.902 :) ) – lmo May 31 '16 at 16:22

2 Answers2

2

Not all matrices have inverses. Check if your matrix is singular i.e. check if its determinant is 0. Singular matrices don't have an inverse.

Vaibhav
  • 971
  • 1
  • 7
  • 8
2

Oops, this matrix is singular:

a <- matrix(1:16, 4, 4)

1  5   9  13
2  6  10  14
3  7  11  15
4  8  12  16

Why? See this:

a[, 3, drop = FALSE] + a[, 2, drop = FALSE] - a[, 1, drop = FALSE]

     [,1]
[1,]   13
[2,]   14
[3,]   15
[4,]   16

exactly a[, 4, drop = FALSE].

A square matrix is invertible, only when it has full column rank, i.e., all its columns are linearly independent. But the columns of this matrix is linearly dependent, i.e., you can write out one column as linear combination of other columns.

In fact, matrices like a <- matrix(1:(n*n), n, n) are singular, for any n > 2. You can prove that those matrices have only a rank of 2, no matter how large n is.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248