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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With