Initialize an Eigen::MatrixXd from a 2d std::vector
Asked Answered
B

1

10

This should hopefully be pretty simple but i cannot find a way to do it in the Eigen documentation.

Say i have a 2D vector, ie

std::vector<std::vector<double> > data

Assume it is filled with 10 x 4 data set.

How can I use this data to fill out an Eigen::MatrixXd mat.

The obvious way is to use a for loop like this:

#Pseudo code
Eigen::MatrixXd mat(10, 4);
for i : 1 -> 10
   mat(i, 0) = data[i][0];
   mat(i, 1) = data[i][1];
   ...
 end

But there should be a better way that is native to Eigen?

Breaking answered 16/9, 2013 at 23:56 Comment(0)
N
14

Sure thing. You can't do the entire matrix at once, because vector<vector> stores single rows in contiguous memory, but successive rows may not be contiguous. But you don't need to assign all elements of a row:

std::vector<std::vector<double> > data;
MatrixXd mat(10, 4);
for (int i = 0; i < 10; i++)
  mat.row(i) = VectorXd::Map(&data[i][0],data[i].size());
Nadean answered 17/9, 2013 at 0:10 Comment(2)
Nice, so that reduces the problem by one, can you do a more complex map over the outside vector?Breaking
@Ben Not from a <vector<vector>>. You could if you had the matrix in a contiguous block of memory in row-major or col-major order.Nadean

© 2022 - 2024 — McMap. All rights reserved.