Reputation: 35
I am having difficulty concatenating vectors in MATLAB.
A = [1
2
3]
B = [6
7
8
9
10]
Desired result:
C = [1
2
3
6
7
8
9
10]
where the sizes of A
and B
are different in every iteration of my script and I want to form the concatenated resulting vector, C
, which has a dynamic size.
This is what I have tried:
Upvotes: 1
Views: 3444
Reputation: 7339
The fool-proof way is this:
C = [A(:);B(:)];
If you use this method then it does not matter if A and B are row vectors, column vectors, or even matrices.
Upvotes: 0
Reputation: 110
Try:
A = [1 2 3];
B = [4 5 6 7 8 9 10];
C = [A B]
For vertical vectors A' and B' use:
C = [A;B]
Upvotes: 0
Reputation: 30047
A = [1
2
3];
B = [6
7
8
9
10];
Vertical concatenation of two vectors/matrices is what you want, done like this...
C = [A; B];
... or this...
C = [A
B];
... or this...
C = vertcat(A,B);
All three of these give
C = [1
2
3
6
7
8
9
10]
% As you requested...
You were running into trouble because you were trying to use horzcat
C = horzcat(A',B');
Horizontal concatenation merges matrices horizontally, i.e.
C = [1, 6
2, 7
3, 8
?, 9
?, 10]
So to avoid this, you've transposed the matrices to make them rows instead of columns, then transposed the result back?? You just need vertcat
! I have shown the shorthand and full form for this above.
Upvotes: 3