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,
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);
}