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/

______________________________________________
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

Reply via email to