106

I was wondering what is your recommended way to compute the inverse of a matrix?

The ways I found seem not satisfactory. For example,

> c=rbind(c(1, -1/4), c(-1/4, 1))  
> c  
      [,1]  [,2]  
[1,]  1.00 -0.25  
[2,] -0.25  1.00  
> inv(c)  
Error: could not find function "inv"  
> solve(c)    
          [,1]      [,2]  
[1,] 1.0666667 0.2666667  
[2,] 0.2666667 1.0666667  
> solve(c)*c  
            [,1]        [,2]  
[1,]  1.06666667 -0.06666667  
[2,] -0.06666667  1.06666667  
> qr.solve(c)*c  
            [,1]        [,2]  
[1,]  1.06666667 -0.06666667  
[2,] -0.06666667  1.06666667  

Thanks!

Tim
  • 1
  • 141
  • 372
  • 590
  • 12
    A general advise: avoid giving objects (like matrices) a name that is already used (here `c`). – Qaswed Dec 10 '16 at 10:52

4 Answers4

174

solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.

24

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

doug
  • 69,080
  • 24
  • 165
  • 199
  • @xeon not sure how you could miss it--see p. 60 of the Manual for the Package referred to in my answer above – doug Jun 06 '14 at 07:23
  • Thank you for your answer. I got this error when running the function fem() from the FisherEM package. Running Mavericks Mac OS X. – Vladislavs Dovgalecs Jun 06 '14 at 15:45
  • very important to note @mathias_Schmidtblaicher's answer about ginv inaccuracy for near singular matrices and lack of speed for large matrices – WetlabStudent Feb 05 '21 at 07:53
9

Note that 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
    +1: I just used solve to invert a near singular matrix (condition number 10^15), it produced a way different answer than ginv. Checking XX^-1 revealed solve did a good job, while ginv produced garbage – WetlabStudent Feb 05 '21 at 07:50
0

Use solve(matrix) if the matrix is larger than 1820x1820. Using inv() from matlib or ginv() from MASS takes longer or will not solve at all because of RAM limits.

patL
  • 2,259
  • 1
  • 17
  • 38