c++ - 特征稀疏矩阵。关于行对非零元素进行排序
问题描述
我有一个稀疏矩阵,我需要存储非零元素和相应的行,列相对于行按升序排列
按照这个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
任何帮助将不胜感激
谢谢!
解决方案
SparseMatrix 有一个可选的模板参数,用于定义存储顺序(参见eigen 文档)。默认情况下,SparseMatrix 使用列优先。所以而不是Eigen::SparseMatrix<double>
使用Eigen::SparseMatrix<double, Eigen::RowMajor>
.
为此使用别名将是有益的
using MyMatrix = Eigen::SparseMatrix<double, Eigen::RowMajor>;
MyMatrix mat(5,5);
推荐阅读
- json - 无法快速将 json 转换为 [String: Any]
- git - `git reset` 和 `git reset --soft` 有什么区别?
- node.js - 使用关联使用范围选择不同的行
- formatting - 如何在 SwiftUI 中将带逗号的十进制数转换为小数(Point)?
- java - Get leading alpha characters from a string in Java/Groovy
- prolog - Prolog检查事实中是否存在a或b
- python - ProcessPoolExecutor 方法为可调用
- sql-server - SSRS 不保存打印机属性
- python - 逐行有条件地修改熊猫数据框中的列的有效方法
- amazon-web-services - 使用参数文件运行TaskCat?