[R] Matrix multiplication using apply() or lappy() ?
Rolf Turner
rolf at erdos.math.unb.ca
Wed Sep 6 18:52:21 CEST 2006
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))
[1] 0.690 0.080 1.051 0.000 0.000
> system.time(for(i in 1:1000) junk <- t(t(a)/a[1,]))
[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))
[1] 7.08 0.99 10.08 0.00 0.00
> system.time(for(i in 1:10000) junk <- t(t(a)/a[1,]))
[1] 5.530 0.940 7.856 0.000 0.000
cheers,
Rolf Turner
More information about the R-help
mailing list