Registered Member
|
Hello Dear Eigen-Developers
I am testing the eigen-libary now, and the matrix multiplication of dense matrices is really fast and also the included trace function. But now I want to do the same procedure with sparse matrices and the multiplication is also fine. But how to get the trace of a sparse matrix? And probably you know how to create an optimized trace function for a product of matrices (in my case 5 matrices). |
Moderator
|
yes, indeed that's not implemented yet. This requires to implement the addressing of the diagonal of a sparse matrix, or in other words to specialize Diagonal<> for Sparse objects. Not very complicated unless we want to do it in an optimal way, e.g., if we know the matrix is triangular then we can do the addressing in constant time...
to optimize trace(A*B*C*D*E), well 1- do the products in the right order to reduce the overall complexity and 2- do the last product to evaluate the diagonal coeffs only. For sparse matrices point 2 would require a special product implementation. |
Registered Member
|
Thank you ggael.
but I'm a newbie in c++ (I did my calculations with mathematica) can you tell me how to create a tracefunction (a little bit more precisely) the only, but really stupid thing, which worked was: typedef Eigen::DynamicSparseMatrix<dcomplex> MatrixComplexEigenSparseDynamic; int sum =0; for (int k=0; k<aux.outerSize(); ++k) for (MatrixComplexEigenSparseDynamic::InnerIterator it(aux,k); it; ++it) { if(it.row() == it.col()) { sum=sum+it.value(); } } std::cout<<" Trace: "<<sum<<std::endl; |
Moderator
|
for this particular case it is faster to do:
int sum =0; for (int k=0; k<aux.outerSize(); ++k) sum += aux.coeff(k,k); as the .coeff method implements a binary search algorithm which is faster than a linear search. |
Registered Member
|
Hello ggael! The last months I was working with the trace of the sparse matrix as you suggested and it it was fast enough. Now I have a code with bigger matrices and I would like to implement a code like SpecialTraceProduct(SparseMatrix_A,SparseMatrix_B) where the sparse matrix product is the trace of these two matrices. Could you (or some one else) suggest how to do this? It would be great ) And I hope it will be one of the next functions implemented in eigen 3.03, because it is really important in many scientific calculations. |
Moderator
|
so you want (A*B).trace(), right?
Then, perhaps an easy to implement solution would be to make sure the A is row major and B is column major, if not you can do copies. Then simply do dot products: double res = 0; for(int i=0, i<.....) res += A.row(i).dot(B.col(i)); this should work. |
Registered users: Bing [Bot], Google [Bot], Yahoo [Bot]