2

当我尝试迭代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

我不明白为什么我得到零,这是怎么回事?

4

1 回答 1

3

根据以下文档SparseMatrix

与压缩格式不同,在两个连续列(分别为行)的非零值之间可能有额外的空间,因此可以通过有限的内存重新分配和复制来插入新的非零值。

[...]

对该函数的调用makeCompressed()将矩阵转换为与许多库兼容的标准压缩格式。

例如

通过示例可以更好地解释此存储方案。以下矩阵

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

及其可能的稀疏列主要表示之一:

Values:       22  7   _   3   5   14  _   _   1   _   17  8
InnerIndices: 1   2   _   0   2   4   _   _   2   _   1   4

[...]

“_”表示可用于快速插入新元素的可用空间。

由于valuePtr()只是返回一个指向Values数组的指针,因此除非您压缩矩阵,否则您将看到空格(打印的零)。

于 2014-08-06T20:18:56.367 回答