Creating an Eigen matrix from an array with row-major order
Asked Answered
W

2

9

I have an array of doubles, and I want to create a 4-by-4 matrix using the Eigen library. I also want to specify that the data is stored in row-major order. How can I do this?

I have tried the following, but it does not compile:

double data[16];
Eigen::Matrix4d M = Eigen::Map<Eigen::Matrix4d>(data, 4, 4, Eigen::RowMajor);
Welltimed answered 25/2, 2015 at 15:27 Comment(2)
What errors do you get?Lawley
What in ggael's answer is lacking? If it answers your question, you should mark it as the answer to your question. If not, post a response with details on what additional help you need.Quinquereme
A
21

You need to pass a row-major matrix type to Map, e.g.:

Map<Matrix<double,4,4,RowMajor> > M(data);

then you can use M as an Eigen matrix, and the values of data will be modified, e.g.:

M = M.inverse();

If you want to copy the data to a true column-major Eigen matrix, then do:

Matrix4d M = Map<Matrix<double,4,4,RowMajor> >(data);

Of course, you can also copy to a row-major matrix by using the right type for M.

Asta answered 26/2, 2015 at 15:23 Comment(1)
Use Dynamic and pass the sizes to the ctor: Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(data, nbRows, nbColumns);Asta
P
3

RowMajor forms actually come in handy when using arrays to store data sometimes. Hence you can also prefer using a typedef to RowMajor type.

namespace Eigen{ 
    typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXfRowMajor;
}

You can replace by float by any datatype of choice. For a 4x4 matrix then, we can simply do

Eigen::MatrixXfRowMajor mat;
mat.resize(4,4);
Pearle answered 31/8, 2021 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.