Suppose I have a C++ vector of vector of double, vector<vector<double> >
. This variable would typically represent the contents of a CSV file, where each row in the file is a sequence of double
values. Each row has the same count of items.
What is the most elegant way to convert this vector<vector<double> >
into a 2-D Eigen MatrixXd?
I was hoping for something like below, where I would like to create a 3x5 matrix from the vector of vector of double.
#include "Eigen/Dense"
#include <vector>
using Eigen::MatrixXd;
int main(int argc, char**argv) {
std::vector<double> row1 = { 1.0, 2.0, 3.0, 4.0, 5.0 };
std::vector<double> row2 = { 11.0, 12.0, 13.0, 14.0, 15.0 };
std::vector<double> row3 = { 21.0, 22.0, 23.0, 24.0, 25.0 };
std::vector<std::vector<double> > vv;
vv.push_back(row1);
vv.push_back(row2);
vv.push_back(row3);
MatrixXd mymatrix(vv); // NOPE! Compiler error.
return 0;
}
Compiling result:
% g++ -std=c++11 test_eigen.cpp
test_eigen.cpp:85:14: error: no matching constructor for initialization of 'MatrixXd' (aka
'Matrix<double, Dynamic, Dynamic>')
MatrixXd matrix(vv); // NOPE!
^ ~~
Note that in Python, converting from a list of list to a Numpy matrix exhibits the simplicity I'm looking for:
import numpy as np
row1 = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
row2 = [ 11.0, 12.0, 13.0, 14.0, 15.0 ]
row3 = [ 21.0, 22.0, 23.0, 24.0, 25.0 ]
list_of_list = [row1, row2, row3];
mymatrix = np.array(list_of_list)
Related question but with 1-D vectors: