Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert eigen matrix into std::vector<std::array<>> form

How can I convert an Eigen matrix into std::vector<std::array<>> form? Suppose I have an Eigen matrix Eigen::MatrixXd A(4,3). Is it possible to convert matrix A in std::vector<std::array<double,3>> form?

like image 496
galib Avatar asked Jun 04 '26 08:06

galib


1 Answers

You can map the memory of a std::vector<std::array<double,3>> to a writable Eigen type using Eigen::Map, e.g.,

// typedef for brevity, if you need this more often: 
typedef Eigen::Matrix<double, 4, 3, Eigen::RowMajor> Mat43dR;

std::vector<std::array<double,3>> raw_data;
raw_data.resize(4); // allocate memory for 4x3 entries
// Copy A to raw_data:
Mat43dR::Map(raw_data[0].data() ) = A;

You can also read from raw_data using Eigen::Map, of course. And there are some alternative ways to work with Eigen::Map: https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html

Addendum: If you don't know the size of A at compile-time, you can work with Dynamic sizes like so:

typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatXXdR;
std::vector<std::array<double,3>> raw_data; // the `3` must still be known at compile-time
assert(A.cols()==3);
raw_data.resize(A.rows()); // allocate memory for Nx3 entries
// Copy A to raw_data:
MatXXdR::Map(raw_data[0].data(), A.rows(), A.cols() ) = A;
like image 134
chtz Avatar answered Jun 06 '26 01:06

chtz