[R] Matrix multiplication using apply() or lappy() ?

Gabor Grothendieck ggrothendieck at gmail.com
Wed Sep 6 19:21:36 CEST 2006

```In terms of speed Toby's original idea was actually the fastest.
Here they are decreasing order of the largest timing in each
row of system.time.  I also tried it with a 100x10 matrix and
got almost the same order:

> library(reshape)
> system.time(for(i in 1:1000) iapply(a, 1, "/", a[1,]))
 11.51  0.01 18.65    NA    NA
> system.time(for(i in 1:1000) t(apply(a, 1, "/", a[1,])))
 0.83 0.00 1.36   NA   NA
> system.time(for(i in 1:1000) sweep(a, 2, a[1,], "/"))
 0.27 0.00 0.39   NA   NA
> system.time(for(i in 1:1000) a/outer(rep(1, nrow(a)), a[1,]))
 0.23 0.00 0.39   NA   NA
> system.time(for(i in 1:1000) a %*% diag(1/a[1,]))
 0.25 0.00 0.38   NA   NA
> system.time(for(i in 1:1000) a/rep(a[1,], each = nrow(a)))
 0.09 0.00 0.16   NA   NA
> system.time(for(i in 1:1000) t(t(a)/a[1,]))
 0.10 0.00 0.13   NA   NA
> system.time(for(i in 1:1000) a/matrix(a[1,], nrow(a), ncol(a), byrow = TRUE))
 0.05 0.00 0.12   NA   NA

> On 9/6/06, Rolf Turner <rolf at erdos.math.unb.ca> wrote:
> Prof. Brian Ripley wrote:
>
> > On Wed, 6 Sep 2006, Christos Hatzis wrote:
> >
> > > See ?sweep
> > >
> > > sweep(a, 2, a[1,],"/")
> >
> > That is less efficient than
> >
> > a/rep(a[1,], each=nrow(a))
>
> *My* first instinct was to use
>
>        t(t(a)/a[1,])
>
> (which has not heretofore been suggested).
>
> This seems to be more efficient still (at least in respect of Prof.
> Grothendieck's toy example) by between 20 and 25 percent:
>
>        > a <- matrix(1:24,4)
>        > system.time(for(i in 1:1000) junk <- a / rep(a[1,], each = 4))
>         0.690 0.080 1.051 0.000 0.000
>        > system.time(for(i in 1:1000) junk <- t(t(a)/a[1,]))
>         0.520 0.120 0.647 0.000 0.000
>        > system.time(for(i in 1:10000) junk <- a / rep(a[1,], each = 4))
>          7.08  0.99 10.08  0.00  0.00
>        > system.time(for(i in 1:10000) junk <- t(t(a)/a[1,]))
>         5.530 0.940 7.856 0.000 0.000
>
>                        cheers,
>
>                                Rolf Turner
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help