I want to write an Eigen dense matrix into a c++ vector. I can preallocate a c++ vector, but it seems I cannot do that on a eigen matrix. I need preallocation, cause i have my reasons. So i want to map the rowmajor ordered matrix into a vector.
I have the address of the matrix written as vector with matrixXd.data()
It prints me an address.
How can i access to its elements? For example I want to store them in another c++ vector
I tried with:
vector<double> array;
for (int i=0; i<6; i++){
array[i] = *mat.data() + i*sizeof(double);
}
But it gives me segmentation fault.
Bugs in your code and discussions on the proper use of std::vector
aside, this should do what you want in an efficient manner.
using RowMajorMatrixXd = Eigen::Matrix<
double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
// could be any Eigen expression
RowMajorMatrixXd x = RowMajorMatrixXd::Random(4, 6);
// allocate vector with size x.rows() * x.cols()
std::vector<double> array(x.size());
// map vector as an Eigen matrix with the appropriate shape
// then assign the content of x
RowMajorMatrixXd::Map(array.data(), x.rows(), x.cols()) = x;
In comments, the use of reshaped
was suggested. I recommend avoiding that since it often produces very inefficient code since mapping indices can be relatively expensive, especially when not known at compile time, and it also disables Eigen's explicit vectorization, though the compiler may still try to do it.