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?
The trace of a matrix A, designated by tr(A), is the sum of the elements on the main diagonal. The sum of the eigenvalues of a matrix equals the trace of the matrix.
The Trace of a Matrix is defined only for a Square Matrix. It is sum of its diagonal elements from the upper left to lower right, of matrix. The Trace of a Matrix is useful to prove the results in Linear Algebra.
Both matrix A and matrix B contains elements from 1 to N*M. Matrix A contains elements in Row-major order and matrix B contains elements in Column-major order. The task is to find the trace of the matrix formed by addition of A and B. Trace of matrix PNXM is defined as P[0][0] + P[1][1] + P[2][2] +…..
Trace of a product The trace of a square matrix which is the product of two real matrices can be rewritten as the sum of entry-wise products of their elements, i.e. as the sum of all elements of their Hadamard product.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With