This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Reordering vector elements

Tags: None
(comma "," separated)
ced
Registered Member
Posts
1
Karma
0

Reordering vector elements

Mon Jul 06, 2015 9:33 am
Hi

This seems so trivial, but I cannot figure out how to do it:

I have a vector v = [ 1 2 3 4 5 ]', and would like to reorder the elements, e.g. Have the 3 last elements be v(1:3), and the first two become v(4:5). in matlab, I could do v = [ v(3:end); v(1:2) ].

If I simply try:
Code: Select all
Eigen::VectorXd v(5);
v << 1,2,3,4,5;

v << v.tail(3), v.head(2);

I get aliasing (as would be expected).

This works:
Code: Select all
v << (Eigen::Vector3d() << v.tail(3)).finished(), (Eigen::Vector2d() << v.head(2)).finished();

but is really ugly.
Is there a simple way to copy/replace elements like that?

Thanks!
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Reordering vector elements

Tue Jul 07, 2015 1:42 pm
You can build a PermutationMatrix:

PermutationMatrix<Dynamic,Dynamic> p(5);
p.indices() << 3,4,0,1,2;
v = p*v;


Bookmarks



Who is online

Registered users: bartoloni, Bing [Bot], Google [Bot], Yahoo [Bot]