[R] Matrix mulitplication
Spencer Graves
spencer.graves at pdf.com
Tue Feb 17 02:03:06 CET 2004
One can also use "crossprod" AND use "solve" to actually "solve"
the system of linear equations rather than just get the inverse, which
is later multiplied by t(BA)%*%D. However, the difference seems very
small:
> set.seed(1)
> n <- 500
> A <- array(rnorm(n^2), dim=c(n,n))
> B <- array(rnorm(n^2), dim=c(n,n))
> C. <- array(rnorm(n^2), dim=c(n,n))
> D <- array(rnorm(n^2), dim=c(n,n))
>
> BA <- B%*%A
>
> start.time <- proc.time()
> A1 <- A%*%solve(t(BA)%*%BA+C.)%*%BA%*%D
> proc.time()-start.time
[1] 4.75 0.03 5.13 NA NA
>
> start.time <- proc.time()
> A2 <- A%*%solve(crossprod(BA)+C., crossprod(t(BA), D))
> proc.time()-start.time
[1] 4.19 0.01 4.49 NA NA
> all.equal(A1, A2)
[1] TRUE
This was in R 1.8.1 under Windows 2000 on an IBM Thinkpad T30 with
a Mobile Intel Pentium 4-M, 1.8Ghz, 1Gbyte RAM. The same script under
S-Plus 6.2 produced the following elapsed times:
[1] 3.325 0.121 3.815 0.000 0.000
[1] 2.934 0.070 3.355 0.000 0.000
Thus, roughly, using "crossprod" plus "solving with solve" gave a
10% speed improvement and S-Plus 6.2 gave a 25% speed improvement in
this one small benchmark. Using smaller matrices did not show as big a
difference just because the time was too short to measure accurately, I
think.
Enough trivia for now.
Best Wishes,
spencer graves
(Ted Harding) wrote:
>On 16-Feb-04 Peter Dalgaard wrote:
>
>
>>(Ted Harding) <Ted.Harding at nessie.mcc.ac.uk> writes:
>>
>>
>>
>>>Sorry! Missed a trick here:
>>>
>>> At <- t(A)
>>> Bt <- t(B)
>>> E <- B%*%A
>>> Et <- t(E)
>>> A%*%solve(Et%*%E + C)%*%Et%*%D
>>>
>>>(saves 2 multiplications at the relatively cheap cost of 1 transpose)
>>>
>>>
>>Well, you might consider getting rid of the first two transposes since
>>you're not actually using them for anything....
>>
>>
>
>Touché ... !
>Ted.
>
>
>--------------------------------------------------------------------
>E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
>Fax-to-email: +44 (0)870 167 1972
>Date: 16-Feb-04 Time: 23:41:57
>------------------------------ XFMail ------------------------------
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
>
More information about the R-help
mailing list