如何访问 C++ 本征稀疏矩阵中的特定(行,列)索引?

How to access a specific (row,col) index in an C++ Eigen sparse matrix?

我在 C++ 中使用 Eigen 中的稀疏矩阵。我想读取存储在特定行和列索引中的数据,就像使用常规特征矩阵一样。

std::vector<Eigen::Triplet<double>> tripletList;

// TODO: populate triplet list with non-zero entries of matrix

Eigen::SparseMatrix<double> matrix(nRows, nCols);
matrix.setFromTriplets(tripletList.begin(), tripletList.end());

// TODO:  set iRow and iCol to be valid indices.

// How to read the value at a specific row and column index?
// double value = matrix(iRow, iCol);  // Compiler error

如何执行此类索引操作?

尝试 coeff:

double value = matrix.coeff(iRow, iCol);

如果您想要非常量版本,请改用 coeffRef。请注意,使用 coeffRef 时,如果该元素不存在,则会插入该元素。

这段代码对我有用

for (int i=0; i<matrix.rows(); ++i){
     for(int j=0; i<matrix.cols(); ++j)
        cout << " i,j=" << i << "," 
             << j << " value=" 
             << matrix.coeff(i,j) 
             << std::endl;
}

这里是原始的方法:

您想要的方法是 innerIndexPtrouterIndexPtrInnerNNZsvaluePtr

struct sparseIndex {
  std::size_t row, col;
  template<class SparseMatrix, class Scalar=typename SparseMatrix::Scalar>
  Scalar get_from( SparseMatrix const& m, Scalar def={} ) const {
    if ((std::size_t)m.cols() >= col) return def;
    auto* inner_index_start = m.innerIndexPtr()+m.outerIndexPtr()[col];
    auto* inner_index_end = inner_index_start;
    if (auto* nzp = m.innerNonZeroPtr()) { // returns null if compressed
      inner_index_end += nzp[col];
    } else {
      inner_index_end = m.innerIndexPtr()+m.outerIndexPtr()[col+1];
    }
    auto search_result = std::equal_range(
      inner_index_start,
      inner_index_end,
      (typename SparseMatrix::StorageIndex)row
    );
    if (search_result.first == search_result.second) return def;
    if ((std::size_t)*search_result.first != row) return def;
    return m.valuePtr()[search_result.first-m.innerIndexPtr()];
  }
};      

使用:

auto r = sparseIndex{2,2}.get_from( sparseMatrix );

代码未经测试。基于 these docs and these docs,在某些细节上存在分歧。

我怀疑我只是重新实现了 .coeff,所以对此持保留态度。 :)