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!