c++使用Eigen讀取Matrix market的.mtx文件中的稀疏矩陣

#include "Eigen/Sparse"
#include "iostream"
#include <vector>
#include "fstream"
#include "algorithm"

using namespace std;
using namespace Eigen;

int main() {
    ifstream fin("/home/dadan/Downloads/494_bus.mtx");
    int M, N, L;
    //Ignore headers and comments
    while (fin.peek() == '%')
        fin.ignore(2048, '\n');

    fin >> M >> N >> L;
    // Eigen::setNbThreads(8);

    SparseMatrix<double, RowMajor> matrix(M, N);
    matrix.reserve(L);
    vector<Eigen::Triplet<double>> triple;
    for (int i = 0; i < L; ++i) {
        int m, n;
        double data;
        fin >> m >> n >> data;
        triple.push_back(Triplet<double>(m - 1, n - 1, data));// m - 1 and n - 1 to set index start from 0
    }
    fin.close();
    matrix.setFromTriplets(triple.begin(), triple.end());

    SparseVector<double, RowMajor> vec(N);

    cout << matrix << endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章