Re: [R] A faster way to calculate Trace?

From: Berwin A Turlach <berwin_at_maths.uwa.edu.au>
Date: Fri 27 Oct 2006 - 00:42:11 GMT

G'day Yongwan,

>>>>> "YC" == YONGWAN CHUN <chun.49@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


R-help@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. Received on Fri Oct 27 10:57:58 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 27 Oct 2006 - 17:30:12 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.