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

前端 未结 7 1184
你的背包
你的背包 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 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    using namespace Eigen;
    
    // load matrix from an ascii text file.
    vector> LoadMatrix(istream* filePath, const string &delim = " \t")
    {
        string line;
        string strnum;
    
        auto data = vector>();
    
        // clear first
        data.clear();
    
        // parse line by line
        while (getline(*filePath, line))
        {
            data.push_back(vector());
    
            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> 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);
    }
    

提交回复
热议问题