[R] trace of matrix product

Robin Hankin r.hankin at noc.soton.ac.uk
Wed Apr 5 12:45:01 CEST 2006


Hi

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




More information about the R-help mailing list