MATLAB: How to combine 2 vectors of unequal length

merging vectors

Hi there
If I have:
A = [1 2 3]
B = [5 6 7 8 9 22 13]
How would I be able to create C=[A(1) B(1) A(2) B(2)…..]
such that when you run out of elements in one vector, the new vector also contains the remaining elements from the longer vector?

Best Answer

One possibility:
A = [1 2 3];
B = [5 6 7 8 9 22 13];
LenA =length(A);
C = zeros(1, LenA+length(B));
C(1:2:LenA*2) = A;
C(2:2:LenA*2) = B(1:LenA);
C(LenA*2+1:end) = B(LenA+1:end)
C =
1 5 2 6 3 7 8 9 22 13
EDIT Originally reversed orders of ‘A’ and ‘B’ in ‘C’. Correct now.