[R] A faster way to calculate Trace?

Berwin A Turlach berwin at maths.uwa.edu.au
Fri Oct 27 02:42:11 CEST 2006


G'day Yongwan,

>>>>> "YC" == YONGWAN CHUN <chun.49 at osu.edu> writes:

    YC> I want to know how to get trace of product of matrices
    YC> **faster** when the matrices are really big. Unfortunately the
    YC> matrices are not symmetric. If anybody know how to get the
    YC> trace of it, please help me. An example is as below.  
The first one is quite simple to speed up:

> n <- 2500
> a <- matrix(rnorm(n*n),n,n)
> b <- matrix(rnorm(n*n),n,n)
> sum(diag(a %*% b))
[1] 1890.638

> tb <- t(b)
> sum(a*tb)
[1] 1890.638

For the second one, you may try:

>  sum(diag(a %*% b %*% a %*% b))
[1] 10668786
> cmat <- a %*% b
> sum(cmat*t(cmat))
[1] 10668786

It gives somewhat a speedup, since you only have to multiply two huge
matrices once instead of thrice, but I wonder whether further
improvements are possible.

Hope this helps.

Cheers,

        Berwin

========================== Full address ============================
Berwin A Turlach                      Tel.: +61 (8) 6488 3338 (secr)   
School of Mathematics and Statistics        +61 (8) 6488 3383 (self)      
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway                   
Crawley WA 6009                e-mail: berwin at maths.uwa.edu.au
Australia                        http://www.maths.uwa.edu.au/~berwin



More information about the R-help mailing list