c++ - Eigen Sparse value_Ptr 显示零,同时忽略有效值

标签 c++ c++11 eigen eigen3

我不明白当我尝试迭代稀疏矩阵的 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.

For example :

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/

相关文章:

c++ - 为 boost::shared_ptr<const Foo> 命名一个 typedef

C++阅读播放列表没有专辑的特定分隔符

android - 将 Eigen 库添加到 Android NDK

c++ - Thrift :从 tSimpleServer 更改为 TNonblockingServer

c++ - 使用 boost::format 只打印小数点后 2 位数字

c++ - 通过 decltype 声明一个 vector

c++ - 构造函数期望指向正在创建的实例的共享指针

c++ - 对于单精度矩阵运算,AVX 与 SSE 的 Eigen 性能没有差异?

c++ - 问一个关于 eigen library with raw buffer 的问题

java - 使一种语言在流控制和另一种语言中不支持原始空检查的字节码指令之间有什么区别?