2017-06-21 79 views
0

我想填补一个稀疏RowMajor矩阵。遵循指南,我使用三元组方法: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) { 
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矩阵的示例,是不可能的?我

回答

1

作品,这里是一个自足的例子:

#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按值得到三元列表和稀疏矩阵,而它们被这个函数修改,所以你mo可能想通过引用传递给他们。

+0

很抱歉忘了将矩阵的初始化添加到显示的代码中,因为它在另一个函数中。我相信用Eigen :: SparseMatrix data_matrix(rows,cols)初始化;'已经设置了大小,对吧? – ClonedOne

+0

事实上,如果使用ColMajor矩阵,你也可以确认它对你有用吗? – ggael

+0

与此同时,我在另一个论坛上找到了另一个解决方案(有趣:))。此刻,我正在执行Eigen :: SparseMatrix data_matrix(cur_rows,cols); data_matrix.reserve(cur_rows * 100000);'并填充'data_matrix.insert(row_iter,words [word_freq [0]])= std :: stoi(word_freq [1]);'它看起来工作正常。你知道两种选择之间是否有明显的性能差异? – ClonedOne