Converting Eigen::MatrixXf to 2D std::vector
Asked Answered
E

1

0

Is there a more elegant solution than to copy the values point to point?!
Something like this works for a 1D vector...

vector<float> vec(mat.data(), mat.data() + mat.rows() * mat.cols());

I tried various other alternatives that were suggested by the GCC compiler for vector< vector > but nothing worked out...

Evanesce answered 24/3, 2015 at 20:40 Comment(0)
C
2

Eigen::MatrixXf uses efficient linear memory, while a vector of vector would represent a very different datatype.

For multidimentional vector, you would therefore have to read the matrix block by block and copy those values to the outmost vectors.

Another way would be to copy the values to a vector based class with specific accessors ... but that would end up reconstructing a Matrix like class.

Why do you want to do that ? What kind of access are you trying to provide ? Maybe you should rather try to do similar access using the eigen::matrix interface

Conversion

Eigen::MatrixXf m(2,3);
std::vector<std::vector<T>> v;

for (int i=0; i<m.rows(); ++i)
{
    const float* begin = &m.row(i).data()[0];
    v.push_back(std::vector<float>(begin, begin+m.cols()));
}
Carnap answered 24/3, 2015 at 21:15 Comment(3)
Its not a matter of choice really... I would rather work with Eigen Matrices however, the Point Cloud Library has its Kmeans API accepting (only 2D vectors). My dataset is huge and I need to use their implementation or otherwise I will have to re-implement my own Kmeans and in that case I must use parallel code (which I'm not exactly sure would work on Eigen Matrices)Evanesce
Been there ... (I use Eigen a lot and don't understand why some library make such crappy api) You have to make a convertion and there is no trivial way as the memory paterns don't matchCarnap
Your implementation would work only if Eigen is setup to use row-major matrices (which is not recommended). Also, just m.col(i).data() would be sufficient (no need to & and [0]).Roorback

© 2022 - 2024 — McMap. All rights reserved.