Combining vectors of different lengths alternatively.

5 次查看(过去 30 天)
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!
  2 个评论
Dave
Dave 2020-4-10
From your description are you wanting to use a loop to take one element at a time for the A and B vectors to create C?
Otherwise the following would provide the C vector in your example.
C = sort([A,B])
miha palcic
miha palcic 2020-4-10
Yes, I would like to take one element at a time alternating between A and B, not just all elements sorted.

请先登录,再进行评论。

采纳的回答

Ameer Hamza
Ameer Hamza 2020-4-10
编辑:Ameer Hamza 2020-4-10
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.

更多回答(0 个)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by