[R] crossprod vs %*% timing

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Oct 6 11:01:34 CEST 2004


t(a) %*% A %*% a is a quadratic form.  What varies `many many times'? If A
does not vary (often), you want to find B with B'B = A (e.g. via chol,
possibly after symmetrizing A) and the squared length of Ba.

Doing the calculations with compiled code calling LAPACK (and making use
of a decent BLAS) would save a lot of overhead.

On Wed, 6 Oct 2004, Robin Hankin wrote:

> Hi
> 
> the manpage says that crossprod(x,y) is formally equivalent to, but
> faster than, the call 't(x) %*% y'.
> 
> I have a vector 'a' and a matrix 'A', and need to evaluate 't(a) %*% A
> %*% a' many many times, and performance is becoming crucial.  With
> 
> f1 <- function(a,X){ ignore <- t(a) %*% X %*% a               }
> f2 <- function(a,X){ ignore <- crossprod(t(crossprod(a,X)),a) }
> f3 <- function(a,X){ ignore <- crossprod(a,X) %*% a           }
> 
> a <- rnorm(100)
> X <- matrix(rnorm(10000),100,100)
> 
> print(system.time( for(i in 1:10000){ f1(a,X)}))
> print(system.time( for(i in 1:10000){ f2(a,X)}))
> print(system.time( for(i in 1:10000){ f3(a,X)}))
> 
> 
> I get something like:
> 
> [1] 2.68 0.05 2.66 0.00 0.00
> [1] 0.48 0.00 0.49 0.00 0.00
> [1] 0.29 0.00 0.31 0.00 0.00
> 
> with quite low variability from run to run.  What surprises me is the
> third figure: about 40% faster than the second one, the extra time
> possibly related to the call to t() (and Rprof shows about 35% of
> total time in t() for my application).
> 
> So it looks like f3() is the winner hands down, at least for this
> task.  What is a good way of thinking about such issues?  Anyone got
> any performance tips?
> 
> I quite often need things like 'a %*% X %*% t(Y) %*% Z %*% t(b)' which
> would be something like
> crossprod(t(crossprod(t(crossprod(t(crossprod(a,X)),t(Y))),Z)),t(b))
> (I think).
> 
> (R-1.9.1, 2GHz G5 PowerPC, MacOSX10.3.5)
> 
> 

-- 
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