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

Sparse matrix addition increasing allocated size

Tags: None
(comma "," separated)
asheshsharma
Registered Member
Posts
1
Karma
0
I am relatively new to Eigen, and am facing the following issue when using sparse matrices in Eigen.

When I use the below code, the allocatedSize for the variable C increases to 20 after addition. I am lost as to why is this happening.

Eigen::SparseMatrix< double > A( 10, 1 );
A.reserve( Eigen::VectorXi::Constant(1,3) );

A.coeffRef( 2, 0 ) = 2;
A.coeffRef( 3, 0 ) = 3;
A.coeffRef( 7, 0 ) = 7;

Eigen::SparseMatrix< double > B( 10, 1 );
B.reserve( Eigen::VectorXi::Constant(1,3) );

B.coeffRef( 0, 0 ) = 0;
B.coeffRef( 1, 0 ) = 1;
B.coeffRef( 8, 0 ) = 8;

Eigen::SparseMatrix< double > C( 10, 1 );
C.reserve( Eigen::VectorXi::Constant(1,6) );

C = A + B;

I face the same issue if I do something like 5*A
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
The reasons are twofolds. First, in this case calling reserve for C is useless because sparse matrix expressions are always evaluated within a temporary and then "moved" into the destination (aka cheap swap of pointers):

temp = A+B;
swap(C,temp);

Then during the evaluation of temp = source_expr, the memory allocated by temp is initialized using the following generic heuristic:

temp.reserve((std::max)(source_expr.rows(),source_expr.cols())*2);

assuming about 2 entries per row or column, which is stupid in the case of sparse vectors.... This heuristic could (should) be improved by propagating upper and lower bounds on the expected numbers of non zeros. Then to cover the following usage pattern:

C.reserve(X); // we know how to accurately compute X
C = .....;

we would need to extend the API with the concept of "in place" evaluation (which is the default for dense matrices), perhaps:

C.inplace() = ....;


Bookmarks



Who is online

Registered users: Bing [Bot], daret, Google [Bot], sandyvee, Sogou [Bot]