How to read CSV file and assign to Eigen Matrix?

后端 未结 3 1300
再見小時候
再見小時候 2020-12-19 15:27

I try to read a large cvs file into Eigen Matrix, below the code found having problem where it can not detect each line of \\n in cvs file to create multiple rows in the mat

3条回答
  •  梦毁少年i
    2020-12-19 15:59

    Here's something you can actually copy-paste

    Writing your own "parser"

    Pros: lightweight and customizable

    Cons: customizable

    #include 
    #include 
    #include 
    
    using namespace Eigen;
    
    template
    M load_csv (const std::string & path) {
        std::ifstream indata;
        indata.open(path);
        std::string line;
        std::vector values;
        uint rows = 0;
        while (std::getline(indata, line)) {
            std::stringstream lineStream(line);
            std::string cell;
            while (std::getline(lineStream, cell, ',')) {
                values.push_back(std::stod(cell));
            }
            ++rows;
        }
        return Map>(values.data(), rows, values.size()/rows);
    }
    

    Usage:

    MatrixXd A = load_csv("C:/Users/.../A.csv");
    Matrix3d B = load_csv("C:/Users/.../B.csv");
    VectorXd v = load_csv("C:/Users/.../v.csv");
    

    Using the armadillo library's parser

    Pros: supports other formats as well, not just csv

    Cons: extra dependency

    #include 
    
    template 
    M load_csv_arma (const std::string & path) {
        arma::mat X;
        X.load(path, arma::csv_ascii);
        return Eigen::Map(X.memptr(), X.n_rows, X.n_cols);
    }
    

提交回复
热议问题