Tr(B'C) is just the inner product of the matrices B and C viewed as vectors. Thus
sum(B*C)
does the trick and is several orders of magnitude faster in this example.
Question
I am looking for a fast computation in R of the trace (trace(A)) of a matrix A = B' C. The fastest way I can think of is the following:
set.seed(123)
n <- 10^6
B <- matrix(rnorm(n), ncol=sqrt(n))
C <- matrix(rnorm(n), ncol=sqrt(n))
ptm <- proc.time()
A <- tcrossprod(B,C)
traceA <- sum(diag(A))
proc.time() - ptm
I am asking myself if there is a faster way (especially if matrix B and matrix C are symmetric or even idempotent). I mean with the line A <- tcrossprod(B,C)
I am computing the whole matrix A, although I just need the sum of the diagonal elements of the matrix (trace(A)).
To speed this up, I thought of a parallel computation for tcrossprod
, but I havn't found an implementation for this (additionally I don't know if this would be a good idea). Does someone have an idea?
Solution
Tr(B'C) is just the inner product of the matrices B and C viewed as vectors. Thus
sum(B*C)
does the trick and is several orders of magnitude faster in this example.