How do i combine two different sized vectors?

A = [1;3;5;7;9;11] and B = [2;4;6;8;10;12;14;16]
to make C = [1;2;3;4;5;6;7;8;9;10;11;12;14;16]

 Accepted Answer

Birdman
Birdman on 15 Nov 2017
Edited: Birdman on 15 Nov 2017
C=sort([A;B])

7 Comments

Thankyou, what if I had want to combine two positive/negative/positive vectors:
X1 = [3;2;1;-1;2;3]
Y1 = [3.5;2.5;1.5;-1.5;2.5;3.5]
So that they retain their initial order?
C = [3.5;3;2.5;2;1.5;1;-1;-1.5;-2;-2.5;-3;-3.5]
Do you want to sort them or not? If not, type
C=[X1;Y1]
sorry meant:
C = [3.5;3;2.5;2;1.5;1;-1;-1.5;2;2.5;3;3.5]
@George Tod: can you please explain the logic of the order of C, which swaps order half-way through:
>> Z = [Y(1);X(1);Y(2);X(2);Y(3);X(3);X(4);Y(4);X(5);Y(5);X(6);Y(6)]
Z =
3.5000
3.0000
2.5000
2.0000
1.5000
1.0000
-1.0000
-1.5000
2.0000
2.5000
3.0000
3.5000
>> isequal(C,Z)
ans = 1
Why does Y(4) not follow X(3) ?

Sign in to comment.

More Answers (1)

Jan
Jan on 15 Nov 2017
Edited: Jan on 15 Nov 2017
It is possible. Assuming, that you data do not contain NaNs:
X1 = [3;2;1;-1;2;3];
Y1 = [3.5;2.5;1.5;-1.5;2.5;3.5];
function C = JoinWithOrder(X, Y)
nX = numel(X);
nY = numel(Y);
C = NaN(2, max(nX, nY));
C(1, 1:nY) = Y(:).';
C(2, 1:nX) = X(:).'; % [EDITED, "C(1" -> "C(2", thanks Andrei!
C = C(~isnan(C));
end

2 Comments

Hi Jan! Maybe so?
C(1, 1:nY) = Y(:).';
C(2, 1:nX) = X(:).';
or
C(2, 1:nY) = Y(:).';
C(1, 1:nX) = X(:).';
@Andrei: Yes. I assume the shown data match to setting the Y values in the first line - perhaps.

Sign in to comment.

Asked:

on 15 Nov 2017

Commented:

Jan
on 15 Nov 2017

Community Treasure Hunt

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

Start Hunting!