Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate vectors in a specific, non-serial ordering

I have vectors a,b and c; vectors a and b contain integer numbers while vector c has binary values as elements: (0,1).

Vector a has length n and vector b has length k. Vector c has length n+k.

I want to concatenate vectors a and b based on vector c.

For example. If c=[1 0 0 1 0 . . . . ] then I want to create vector res=[a(1) b(1) b(2) a(2) b(3) . . . ].

Is there any way to do so without a for loop?

like image 213
Wanderer Avatar asked Mar 13 '23 15:03

Wanderer


1 Answers

res = c; %// copy c for the result vector
res(c) = a;
res(~c) = b;

using logical indexing! This works because the number of 0 elements in c is exactly equal to the number of elements in b and the number of 1 elements equals the number of elements in a. Logical operators for indexing thanks to @Dan's comment

like image 194
Adriaan Avatar answered Mar 24 '23 08:03

Adriaan