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

Computing Tr(AB) efficiently?

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

Computing Tr(AB) efficiently?

Tue Jan 13, 2015 12:55 am
Hello,

I'm trying to compute Tr(AB) efficiently where A, B are Hermitian (self-adjoint) matrices and Tr is the matrix trace.

The current code I've got is:
Code: Select all
real((a.array() * b.array()).sum());

Noting that Tr(AB) = AB_{ii} = A_{ij}B_{ji} = A_{ij}B_{ij}, via Einstein's index convention. I'd like to use this trick since it doesn't use matrix multiplication. Furthermore, I'd like to use the triangularView mechanism to exploit the fact that A and B are Hermitian. I want to sum the lower off-diagonal terms, multiply that by 2, and add the sum of the diagonal terms. How does one go about this?
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Computing Tr(AB) efficiently?

Tue Jan 13, 2015 10:39 pm
In theory you could write something like:
Code: Select all
F.cwiseProduct(G).triangularView<StrictlyUpper>().sum()*2 + F.cwiseProduct(G).diagonal().sum()

but reductions on triangular-views are not implemented yet.

Note that because of the overhead to vectorize a reduction on a triangular part, speedup would be expected for large matrices only, like larger than 100x100.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Computing Tr(AB) efficiently?

Tue Jan 13, 2015 10:42 pm
To get an idea of what could be the speed up, you can try a manual for loop:
Code: Select all
tr = 0;
for(Index j=1; j<A.cols(); ++j)
  tr += A.cwiseProduct(B).cols(j).head(j);
tr = tr*2 + A.cwiseProduct(B).diagonal().sum()

Let us know if you get a significant speed up. If so, this might motivate us to implement triangular reductions!


Bookmarks



Who is online

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