C++ 三元组特征填充稀疏行主矩阵

C++ 三元组特征填充稀疏行主矩阵,c++,sparse-matrix,eigen,C++,Sparse Matrix,Eigen,我正在尝试填充稀疏的行主矩阵。按照指南,我使用了三联体方法: 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) { u

我正在尝试填充稀疏的行主矩阵。按照指南,我使用了三联体方法:

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());
Eigen::SparseMatrix数据矩阵(行、列);
....
void get_data(const char*dir_name,std::vector三元组列表,Eigen::SparseMatrix data_矩阵){
uint64世界其他地区的iter=0;
对于(std::字符串文件\n:已排序的\u文件){
...
if(words.find(word\u freq[0])!=words.end()
三重列表。向后推(T(行,单词[word\u freq[0]),std::stoi(word\u freq[1]);
}
国际热核试验堆++;
}
数据矩阵.setFromTriplets(TripleList.begin(),TripleList.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";
}
编辑:


所以问题在于代码的结构,我看到
get_data
按值获取三元组列表和稀疏矩阵,而它们是由这个函数修改的,所以您很可能希望通过引用来传递它们。

很抱歉,忘了将矩阵的初始化添加到显示的代码中,因为它是在另一个函数中。我相信使用
Eigen::SparseMatrix data_矩阵(rows,cols)初始化
已经设置了大小,对吗?确实如此,如果使用
ColMajor
矩阵,那么您能确认它确实对您有效吗?与此同时,我在另一个论坛上的一个答案中找到了另一种解决方案(有趣:)。现在我正在做
Eigen::SparseMatrix data_矩阵(cur_rows,cols);数据矩阵储备(当前行*100000)并用
数据矩阵填充。插入(行,字[word\u freq[0]]=std::stoi(word\u freq[1])而且它似乎工作得很好。您知道这两个备选方案之间是否存在明显的性能差异吗?但它仍应适用于setFromTriplets,我的自包含示例显示了这一点。好的,当我有时间进行测试时,我将尝试使用triplets方法,并让您知道。同时,我将选择您的答案作为已接受:)
 1  0  0  8  4  0  0
 0  3  0  6  0  0  0
16  0  0  2  0  0  5