Inversa de la matriz en R


Me preguntaba cuál es su forma recomendada de calcular la inversa de una matriz?

Las formas que encontré no parecen satisfactorias. Por ejemplo,

> 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  

Gracias!

Author: Tim, 2010-11-20

4 answers

solve(c) da el inverso correcto. El problema con su código es que está utilizando el operador incorrecto para la multiplicación de matrices. Debe usar solve(c) %*% c para invocar la multiplicación de matrices en R.

R realiza la multiplicación elemento por elemento cuando invoca solve(c) * c.

 127
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-20 01:13:35

Puede utilizar la función ginv() (Moore-Penrose generalizada inversa) en el MASA paquete

 20
Author: doug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-06 07:25:04

Tenga en cuenta que si se preocupa por la velocidad y no necesita preocuparse por las singularidades, solve() debe preferirse a ginv() porque es mucho más rápido, como puede comprobar:

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 
 7
Author: Matthias Schmidtblaicher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-27 16:37:57

En notación matricial se hace una gran diferencia el operador "*" y el operador "%*%". El primero hace la multiplicación elemento por elemento, el segundo es la fórmula correcta para la multiplicación de matrices. Lo que hou debería haber hecho es:

c = rbind(c(1, -1/4), c(-1/4, 1))

solve(c) %*% c
 1
Author: Cerbero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-10 12:44:50