Medoalmasry
Medoalmasry

Reputation: 546

Converting Eigen::MatrixXf to 2D std::vector

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...

Upvotes: 0

Views: 2564

Answers (1)

Amxx
Amxx

Reputation: 3070

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()));
}

Upvotes: 2

Related Questions