我不明白当我尝试迭代稀疏矩阵的 valuePtr
时得到的结果。这是我的代码。
#include <iostream>
#include <vector>
#include <Eigen/Sparse>
using namespace Eigen;
int main()
{
SparseMatrix<double> sm(4,5);
std::vector<int> cols = {0,1,4,0,4,0,4};
std::vector<int> rows = {0,0,0,2,2,3,3};
std::vector<double> values = {0.2,0.4,0.6,0.3,0.7,0.9,0.2};
for(int i=0; i < cols.size(); i++)
sm.insert(rows[i], cols[i]) = values[i];
std::cout << sm << std::endl;
int nz = sm.nonZeros();
std::cout << "non_zeros : " << nz << std::endl;
for (auto it = sm.valuePtr(); it != sm.valuePtr() + nz; ++it)
std::cout << *it << std::endl;
return 0;
}
Output:
0.2 0.4 0 0 0.6 // The values are in the matrix
0 0 0 0 0
0.3 0 0 0 0.7
0.9 0 0 0 0.2
non_zeros : 7
0.2 // but valuePtr() does not point to them
0.3 // I expected: 0.2, 0.3, 0.9, 0.4, 0.6, 0.7, 0.2
0.9
0
0.4
0
0
我不明白为什么我会得到零,这是怎么回事?
最佳答案
根据documentation对于稀疏矩阵:
Unlike the compressed format, there might be extra space inbetween the nonzeros of two successive columns (resp. rows) such that insertion of new non-zero can be done with limited memory reallocation and copies.
[...]
A call to the function
makeCompressed()
turns the matrix into the standard compressed format compatible with many library.
This storage scheme is better explained on an example. The following matrix
0 3 0 0 0 22 0 0 0 17 7 5 0 1 0 0 0 0 0 0 0 0 14 0 8
and one of its possible sparse, column major representation:
Values: 22 7 _ 3 5 14 _ _ 1 _ 17 8 InnerIndices: 1 2 _ 0 2 4 _ _ 2 _ 1 4
[...]
The "_" indicates available free space to quickly insert new elements.
由于 valuePtr()
只是返回一个指向 Values
数组的指针,因此除非您压缩矩阵,否则您将看到空格(打印的零) .
关于c++ - Eigen Sparse value_Ptr 显示零,同时忽略有效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25169229/