【问题标题】:Eigen Sparse matrix. Sorting non-zero elements with respect to rows特征稀疏矩阵。相对于行对非零元素进行排序
【发布时间】:2019-07-03 10:33:40
【问题描述】:

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

关注这个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-matrix eigen


【解决方案1】:

SparseMatrix 有一个可选的模板参数,用于定义存储顺序(参见eigen documentation)。默认情况下,SparseMatrix 使用列优先。所以不要使用Eigen::SparseMatrix&lt;double&gt;,而是使用Eigen::SparseMatrix&lt;double, Eigen::RowMajor&gt;

为此使用别名会很有好处

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

【讨论】:

  • 我得到这个错误 'Eigen::SparseCompressedBase::InnerIterator::InnerIterator(const Eigen::SparseMatrixBase&, Eigen::Index) [with T = Eigen::SparseMatrix ;派生 = Eigen::SparseMatrix; Eigen::Index = long int]' 在此上下文中是私有的 (Eigen::SparseMatrix::InnerIterator it(mat,k); it; ++it)
  • 你必须使用正确的迭代器:'MyMatrix::InnerIterator'
猜你喜欢
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 2022-10-23
  • 2017-06-05
  • 2013-09-25
  • 2011-09-29
  • 2021-06-16
  • 2012-11-15
相关资源
最近更新 更多