MATLAB: Combining vectors of different lengths alternatively.

combine vectorsvectors

I'm trying to combine two vectors, using one element from each per step.
Say A = [1,3,5] and B = [ 2,4]
I would like to combine them to C =[1,2,3,4,5]
Vectors A and B can either be equal of length or differ by maximum of 1.
One can also be empty and the other of size 1.
I have tried various solutions I found online but Mathlab throws "Error using vertcat/horzcar", since sometimes the vectors differ in length.
Thanks in advance!

Best Answer

Try this
clear C
A = [7 2 3];
B = [1 4];
na = numel(A);
nb = numel(B);
if na > nb
C([1:2:na*2-1 2:2:nb*2]) = [A B];
else
C([2:2:na*2 1:2:nb*2-1]) = [A B];
end
Result:
C =
7 1 2 4 3
The following one-liner is a bit cryptic but works correct
clear C
A = [7 2 3];
B = [1 4];
na = numel(A);
nb = numel(B);
C([1+(na<nb):2:na*2-(na>nb) 1+(nb<na):2:nb*2-(nb>na)]) = [A B];
Note: If the number of elements in B is higher then A, then the resulting vector C starts with the first element of B.