Eigen 用三元组填充稀疏 RowMajor 矩阵

Eigen fill up Sparse RowMajor matrix with triplets

我正在尝试填充稀疏 RowMajor 矩阵。按照指南,我使用的是三胞胎法:

Eigen::SparseMatrix<double, Eigen::RowMajor> data_matrix(rows, cols);
....

void get_data(const char *dir_name, std::vector<T> tripletList, Eigen::SparseMatrix<double, Eigen::RowMajor> data_matrix) {
uint64_t row_iter = 0;

for (std::string file_n : sorted_files) {
   ...
   if (words.find(word_freq[0]) != words.end())
       tripletList.push_back(T(row_iter, words[word_freq[0]], std::stoi(word_freq[1])));
   }

   row_iter++;

}

data_matrix.setFromTriplets(tripletList.begin(), tripletList.end());

但是,这种方法会生成一个空矩阵。我找不到用三元组列表方法填充 RowMajor 矩阵的示例,这不可能吗?

对我有用,这是一个独立的例子:

#include <iostream>
#include <Eigen/SparseCore>
#include <vector>
using namespace Eigen;
using namespace std;

int main()
{
  int m = 3, n = 7;
  SparseMatrix<double, RowMajor> M(m,n);
  typedef Triplet<double,int> T;
  vector<T> entries;
  for(int k=1; k<=9;++k)
    entries.push_back( T(internal::random<int>(0,m-1), internal::random<int>(0,n-1), k) );
  M.setFromTriplets(entries.begin(), entries.end());
  cout << MatrixXd(M) << "\n";
}

产生:

 1  0  0  8  4  0  0
 0  3  0  6  0  0  0
16  0  0  2  0  0  5

编辑:

所以问题出在你的代码结构上,我看到 get_data 通过值获取三元组列表和稀疏矩阵,而它们是由这个函数修改的,所以你很可能想通过他们通过参考。