4

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?

Dan
  • 45,079
  • 17
  • 88
  • 157
Wanderer
  • 253
  • 1
  • 12

1 Answers1

7
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

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75