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?

lorniper
  • 626
  • 1
  • 7
  • 29
  • @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` to improve readability. – chtz Dec 06 '16 at 10:32
  • @chtz, I know, I wanted to hear from OP that that's what was meant – Avi Ginsburg Dec 06 '16 at 10:34
  • @AviGinsburg meaning the rows and column is not a constant, it works with Eigen::MatrixXd M=Eigen::Map(p, row, col), but then I cannot change the colmajor – lorniper Dec 06 '16 at 10:36

1 Answers1

6

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";
Avi Ginsburg
  • 10,323
  • 3
  • 29
  • 56
  • So, I should write Eigen::Map>(p, row, col), if row and col are not known at compile time? – lorniper Dec 06 '16 at 10:40
  • Yes. You might want to take [chtz's](http://stackoverflow.com/questions/40992984/mapping-row-major-array-to-column-majored-eigen-matrix#comment69194963_40992984) advice re: typedef for readability. – Avi Ginsburg Dec 06 '16 at 10:42