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

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Sep 6 19:30:31 CEST 2006


What version of R was this?

In 2.4.0 alpha

> a <- matrix(1:24,4)
> system.time(for(i in 1:1000) junk <- a / rep(a[1,], each = 4))
[1] 0.014 0.000 0.014 0.000 0.000
> system.time(for(i in 1:1000) junk <- t(t(a)/a[1,]))
[1] 0.057 0.000 0.058 0.000 0.000

shows a large margin the other way, which increases with bigger matrices

> a <- matrix(pi*1:100, 100, 1000)
> system.time(for(i in 1:1000) junk <- t(t(a)/a[1,]))
[1] 18.329  2.238 20.595  0.000  0.000
> system.time(for(i in 1:1000) junk <- a / rep(a[1,], each = 4))
[1] 2.589 1.021 3.610 0.000 0.000


On Wed, 6 Sep 2006, Rolf Turner 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))
> 	[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
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list