Eigen library --> initialize matrix with data from file or existing std::vector content (c++)

前端 未结 7 1121
你的背包
你的背包 2020-12-25 08:00

My question is how to initialize an eigen Matrix, but NOT this way:

matrix << 1,0,1,0,
          1,0,1,0,
          1,0,1,0,


        
相关标签:
7条回答
  • 2020-12-25 08:58

    Here is my solution:

    #include <istream>
    #include <string>
    #include <sstream>
    #include <vector>
    #include <fstream>
    #include <iostream>
    #include <eigen>
    
    using namespace std;
    using namespace Eigen;
    
    // load matrix from an ascii text file.
    vector<vector<double>> LoadMatrix(istream* filePath, const string &delim = " \t")
    {
        string line;
        string strnum;
    
        auto data = vector<vector<double>>();
    
        // clear first
        data.clear();
    
        // parse line by line
        while (getline(*filePath, line))
        {
            data.push_back(vector<double>());
    
            for (string::const_iterator i = line.begin(); i != line.end(); ++i)
            {
                // If i is not a delim, then append it to strnum
                if (delim.find(*i) == string::npos)
                {
                    strnum += *i;
                    if (i + 1 != line.end()) // If it's the last char, do not continue
                        continue;
                }
    
                // if strnum is still empty, it means the previous char is also a
                // delim (several delims appear together). Ignore this char.
                if (strnum.empty())
                    continue;
    
                // If we reach here, we got a number. Convert it to double.
                double       number;
    
                istringstream(strnum) >> number;
                data.back().push_back(number);
    
                strnum.clear();
            }
        }
        return data;
    }
    
    Eigen::MatrixXd ConvertToEigenMatrix(std::vector<std::vector<double>> data)
    {
        Eigen::MatrixXd eMatrix(data.size(), data[0].size());
        for (int i = 0; i < data.size(); ++i)
            eMatrix.row(i) = Eigen::VectorXd::Map(&data[i][0], data[0].size());
        return eMatrix;
    }
    MatrixXd LoadEigenMatrix(istream* filePath, const string &delim = " \t")
    {
        auto data = LoadMatrix(filePath, delim);
        return ConvertToEigenMatrix(data);
    }
    
    0 讨论(0)
提交回复
热议问题