[R] trace of matrix product

Ken Knoblauch knoblauch at lyon.inserm.fr
Wed Apr 5 18:15:09 CEST 2006


How about ;

m <- matrix(rnorm(9), ncol = 3)
mm <- matrix(rnorm(9), ncol = 3)
sum(sapply(1:3, function(i, m, mm) m[i, ] %*% mm[ ,i], m, mm))

**********************************
what is the best way to calculate the trace of a product
of two matrices?

If

A <- matrix(rnorm(48),nrow=6)
B <- matrix(rnorm(48),nrow=8)


Is there a better (faster, more elegant) way to compute the trace of
A%*%B  than


sum(diag(A %*% B))?


I would call the above solution inelegant because all
the elements of A %*% B are calculated, when one
really only needs the elements on the diagonal.
It  also uses %*% instead of crossprod() or trcrossprod()







--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743


*****************************
-- 
Ken Knoblauch
Inserm U371
Cerveau et Vision
Dept. of Cognitive Neuroscience
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.lyon.inserm.fr/371/




More information about the R-help mailing list