Mapping row-major array to column-majored Eigen Matrix
Asked Answered
P

1

6

I want to map from a C-type array to a Column majored Eigen matrix.

The mapping itself is using the RowMajor type,

so I tried

std::vector<double> a(9);
double *p= a.data();
Eigen::MatrixXd M=Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(p)

I got what I expected(the order of M.data()), however, if the dimension(3) in the template is not known at compile time, this method doesn't work... any solution?

Petrarch answered 6/12, 2016 at 10:23 Comment(3)
@AviGinsburg That is the correct solution, except that you also need to pass the number of rows and columns (not only the pointer) in this case. Generally, it makes sense to make a typedef for Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> to improve readability.Vazquez
@chtz, I know, I wanted to hear from OP that that's what was meantTurmel
@AviGinsburg meaning the rows and column is not a constant, it works with Eigen::MatrixXd M=Eigen::Map<Eigen::MatrixXcd>(p, row, col), but then I cannot change the colmajorPetrarch
T
7

I assume that you wrote:

Eigen::MatrixXd M=Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(p);

This doesn't let the map know what the dimensions should be. You have to add that in the constructor:

std::vector<double> a{1,2,3,4,5,6,7,8,9};
double *p = a.data();
std::cout << Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>(p) << "\n\n";
std::cout << Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(p, 3, 3) << "\n\n";

std::cout << Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::ColMajor>>(p) << "\n\n";
std::cout << Eigen::Map<Eigen::MatrixXd>(p, 3, 3) << "\n\n";
Turmel answered 6/12, 2016 at 10:36 Comment(2)
So, I should write Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(p, row, col), if row and col are not known at compile time?Petrarch
Yes. You might want to take chtz's advice re: typedef for readability.Turmel

© 2022 - 2024 — McMap. All rights reserved.