Finding inverse matrix in R

4.9k Views Asked by At

I have a variance covariance matrix S:

> S
     [,1] [,2]
[1,]    4   -3
[2,]   -3    9

I am trying to find an inverse of it.

The code I have is:

>invS <- (1/((S[1,1]*S[2,2])-(S[1,2]*S[2,1])))*S
           [,1]       [,2]
[1,]  0.1481481 -0.1111111
[2,] -0.1111111  0.3333333

However, if I use solve(), I get this:

>invSalt <- solve(S)
          [,1]      [,2]
[1,] 0.3333333 0.1111111
[2,] 0.1111111 0.1481481

Why is invS incorrect? What should I change to correct it?

2

There are 2 best solutions below

0
On BEST ANSWER

You correctly found the determinant in the denominator, but the rest is wrong.

enter image description here

Off-diagonal elements should be with the opposite sign, while the diagonal elements should be switched. Both of those things are clearly visible when comparing the two matrices.

That's not the most convenient thing to do by hand, so solve is really better. If you insist on doing it manually, then you could use

matrix(rev(S), 2, 2) / (prod(diag(S)) - S[1, 2] * S[2, 1]) * (2 * diag(1, 2) - 1)
#           [,1]      [,2]
# [1,] 0.3333333 0.1111111
# [2,] 0.1111111 0.1481481
0
On

The correct formula is

 (1/((S[1,1]*S[2,2])-(S[1,2]*S[2,1])))* matrix(c(S[2,2], -S[2,1], -S[1,2], S[1,1]),2)