[R] trace of matrix product
Carlos J. Gil Bellosta
cgb at datanalytics.com
Wed Apr 5 12:46:21 CEST 2006
Try
sum( rowSums( A * t(B)) )
Then you do not make any calculation you do not really need.
Carlos J. Gil Bellosta
http://www.datanalytics.com
Quoting Robin Hankin <r.hankin at noc.soton.ac.uk>:
> 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
>
> ______________________________________________
> R-help at 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
>
More information about the R-help
mailing list