Sara Fiore
Sara Fiore

Reputation: 3

Eigen Sparse matrix. Sorting non-zero elements with respect to rows

I have a sparse matrix and I need to store the non-zero elements and respective row,column in ascending order with respect to rows

following this https://eigen.tuxfamily.org/dox/group__TutorialSparse.html I tried

// mat =
// 1.0, 0.0, 1.0, 0.0, 0.0
// 1.0, 0.0, 0.0, 0.0, 1.0
// 0.0, 1.0, 0.0, 0.0, 0.0
// 0.0, 0.0, 1.0, 0.0, 1.0
// 1.0, 0.0, 0.0, 1.0, 0.0 

// create and fill the sparse matrix
SparseMatrix<double> mat(5,5);
mat.insert(0,0) = 1.0;
mat.insert(0,2) = 1.0;
mat.insert(1,0) = 1.0;
mat.insert(1,4) = 1.0;
mat.insert(2,1) = 1.0;
mat.insert(3,2) = 1.0;
mat.insert(3,4) = 1.0;
mat.insert(4,0) = 1.0;
mat.insert(4,3) = 1.0;

//matrix where to store the row,col,value
Eigen::MatrixXd mat_map(mat.nonZeros(),3);

int index_mat;
index_mat=-1;

for (int k=0; k<mat.outerSize(); ++k)
  for (SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)
   {
     index_mat++;
     mat_map(index_mat,0) = it.row();   // row index
     mat_map(index_mat,1) = it.col();   // col index 
     mat_map(index_mat,2) = it.value();
   }


cout << mat_map << endl;

what I get is the following

0 0 1.0
1 0 1.0
4 0 1.0
2 1 1.0
0 2 1.0
3 2 1.0
4 3 1.0
1 4 1.0
3 4 1.0

while what I want is

0 0 1.0
0 2 1.0 
1 0 1.0
1 4 1.0
2 1 1.0  
3 2 1.0
3 4 1.0
4 0 1.0
4 3 1.0

Any help will be appreciated

thanks!

Upvotes: 0

Views: 354

Answers (1)

Lukas Engelke
Lukas Engelke

Reputation: 174

SparseMatrix has an optional template parameter that defines the storage order (cf. eigen documentation). By default, SparseMatrix uses column-major. So instead of Eigen::SparseMatrix<double> use Eigen::SparseMatrix<double, Eigen::RowMajor>.

It would be beneficial to use an alias for this

using MyMatrix = Eigen::SparseMatrix<double, Eigen::RowMajor>;
MyMatrix mat(5,5);

Upvotes: 0

Related Questions