Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to flatten an Eigen matrix without copying?

Tags:

c++

eigen

Suppose you have a matrix A:

1 2
3 4

There are two flattenings:

1
2
3
4

and

1
3
2
4

If the default (ColMajor) storage type is used, we can get the latter as

VectorXd v = Map<const VectorXd>(A.data(), A.size())

This only copies the data once.

But to get the former, the best I can think of is

MatrixXd At = A.transpose()
VectorXd v  = Map<const VectorXd>(At.data(), At.size())

This copies the data twice, unfortunately.

Somewhat confusingly (to me at least)

VectorXd v  = Map<const VectorXd>(A.transpose().data(), A.size())

compiles, but produces completely identical results as not having the transpose there.

See also: Eigen Convert Matrix to Vector

like image 855
user357269 Avatar asked Oct 10 '16 05:10

user357269


1 Answers

Note that you can name a Map object:

Map<const VectorXd> v1(A.data(), A.size());

and use v1 like a VectorXd. Of course, modifying v1 will also modify A. To pass it to functions accepting a const VectorXd& object without copy, either make your function template or make take a Ref<const VectorXd>.

Then the first case requires zero copy, and the second 1 transposed copy.

like image 126
ggael Avatar answered Sep 22 '22 08:09

ggael