This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Trace of matrix product

Tags: None
(comma "," separated)
marcalexa
Registered Member
Posts
1
Karma
0

Trace of matrix product

Wed Feb 05, 2014 1:12 pm
Hi,

I apologize if this is obvious or has been treated before (I have only found the outer product of vectors being discussed in this aspect). I want to compute the trace of a matrix-matrix product, i.e. given two (large) square matrices A,B, I want to compute tr(AB). Would Eigen be able to use expression templates on this and only evaluate the row-vector products necessary for the diagonal elements of the product? What is the right way to implement this?

Addition to the first question: B is in fact very sparse, only few columns contain non-zero elements. Can this be exploited automagically, i.e. only computing the very few row-column products that would evaluate to non-zero diagonal entries in the product; and, further, would the trace function recognize the diagonal of the matrix is sparse and sum only over the non-zero entries?

Thanks!
-Marc
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Trace of matrix product

Wed Feb 05, 2014 2:35 pm
Hi,

with a not too old version of Eigen, (A*B).diagonal().sum() with A and B dense will be fully optimized (no useless computation, no temporary).

If one is sparse, then (A*B).diagonal() will be assumed to be dense and taking the sum will boils down to something like:

for(int k=0; k<diag_size;++k)
trace += A.row(k).dot(B.col(k));

This dot product will iterate on the non-zeros only, but we cannot turn this dense for loop into a sparse one because the SparseMatrix representation is designed for non-empty columns.


Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], Google [Bot], Yahoo [Bot]