[R] inverse matrix

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Oct 28 13:32:32 CEST 2005


Sundar Dorai-Raj <sundar.dorai-raj at pdf.com> writes:

> Sam R. Smith wrote:
> > if solve(a,b) means to calculate an inverse matrix of
> > a with b, and i wonder why solve(a)%%b will get
> > different result?
> > 
> 
> It does? Or perhaps your "%%" is not just a typo. It should be "%*%".
> 
>  > a <- matrix(rnorm(16), 4, 4)
>  > b <- matrix(rnorm(4), 4, 1)
>  > solve(a, b)
>             [,1]
> [1,] -0.8005768
> [2,]  0.5913755
> [3,] -1.8256012
> [4,]  0.8973716
>  > solve(a) %*% b
>             [,1]
> [1,] -0.8005768
> [2,]  0.5913755
> [3,] -1.8256012
> [4,]  0.8973716

I think the issue is this:

>  solve(a, b)
[1] -0.7251033 -0.3903765  0.3212044 -1.2969697
>  solve(a)%*% b
           [,1]
[1,] -0.7251033
[2,] -0.3903765
[3,]  0.3212044
[4,] -1.2969697

So b gets promoted to a column matrix in one case but not the other. 

This is slightly odd, but it's been that way "forever" and in S(-PLUS)
too, so I think it is unchangeable (it's the sort of thing that
there's a 99% chance that some people have actually been relying on). 

If you want a vector result from a matrix multiply, there's always
> drop(solve(a)%*% b)
[1] -0.7251033 -0.3903765  0.3212044 -1.2969697


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list