首页 > 解决方案 > 特征稀疏矩阵。关于行对非零元素进行排序

问题描述

我有一个稀疏矩阵,我需要存储非零元素和相应的行,列相对于行按升序排列

按照这个https://eigen.tuxfamily.org/dox/group__TutorialSparse.html 我试过了

// 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;

我得到的是以下

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

而我想要的是

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

任何帮助将不胜感激

谢谢!

标签: c++sparse-matrixeigen

解决方案


SparseMatrix 有一个可选的模板参数,用于定义存储顺序(参见eigen 文档)。默认情况下,SparseMatrix 使用列优先。所以而不是Eigen::SparseMatrix<double>使用Eigen::SparseMatrix<double, Eigen::RowMajor>.

为此使用别名将是有益的

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

推荐阅读