Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trace of a crossproduct-matrix - a faster computation?

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?

like image 241
Giuseppe Avatar asked Jul 30 '13 15:07

Giuseppe


People also ask

What does the trace of a matrix tell you?

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.

Why is the trace of a matrix useful?

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.

What is the trace of a column matrix?

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] +…..

What is the trace of product of matrices?

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.


1 Answers

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.

like image 185
whuber Avatar answered Nov 14 '22 21:11

whuber