How to combine multiple nx1 size of matrix into one matrix

13 views (last 30 days)
As topic mentioned, i want to combine a matrix from many nx1 size matrix, i would like to have a script
Many Thnkas, Alex
  3 Comments
NG
NG on 12 Aug 2014
For example, I got matrix A, A=[1;2;3], and B, B=[4;5;6;7]. I want to combine them to be matrix C, C=[1;2;3;4;5;6;7], but now i got many matrix with differnet number of rows. How can i combine them ? Thanks!
tran thang
tran thang on 10 Oct 2015
Hi! You can reference my code! Good lucky! >> a{1} = [1 1 1;1 1 1]; >> a{1}
ans =
1 1 1
1 1 1
>> a{2} = [2 2 2;2 2 2]; >> a{3} = [3 3 3]; >> a{4} = [4 4 4;4 4 4;4 4 4]; >> a{5} = [5 5 5;5 5 5]; >> A = vertcat(a{:})
A =
1 1 1
1 1 1
2 2 2
2 2 2
3 3 3
4 4 4
4 4 4
4 4 4
5 5 5
5 5 5

Sign in to comment.

Accepted Answer

Matt J
Matt J on 12 Aug 2014
could you plz exlpain more about vertcat(matrices{:}); by showing an example.
>> matrices={[1,2;3 4],[5,6;7,8]};
>> vertcat(matrices{:})
ans =
1 2
3 4
5 6
7 8
  6 Comments
Michael Haderlein
Michael Haderlein on 12 Aug 2014
The first step to fix it is to show the code which is throwing this error ;-)

Sign in to comment.

More Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 12 Aug 2014
Edited: Azzi Abdelmalek on 12 Aug 2014

Joakim Magnusson
Joakim Magnusson on 12 Aug 2014
Edited: Joakim Magnusson on 12 Aug 2014
Where do you have your matrices? If you can get them into cell arrays like this:
matrices = cell(1,2);
matrices{1} = A;
matrices{2} = B;
C = [];
Then you could do like this:
for i = 1:size(matrices,2)
C = [C ;cell2mat(matrices(i))]
end
I'm not sure how you want to combine your matrices but hope this was at least a little helpful.
  4 Comments
NG
NG on 12 Aug 2014
Matt , could you plz exlpain more about vertcat(matrices{:}); by showing an example. Thank You!
Michael Haderlein
Michael Haderlein on 12 Aug 2014
Thanks @Matt, I didn't use cell2mat a lot, so I didn't think about it too much. Your solution is very elegant.

Sign in to comment.


Joakim Magnusson
Joakim Magnusson on 12 Aug 2014
Edited: Joakim Magnusson on 12 Aug 2014
Sorry, i want to clarify that now i am using a loop to generate matrices out and then store them into a new matrix .Can i still use vertcat?
NG, do you mean like this?
B = [];
for i = 1:10
A = magic(4);
A(:, 2:4) = [];
B = vertcat(B, A);
end
  2 Comments
Matt J
Matt J on 12 Aug 2014
That would not be recommendable. With B growing inside the loop, you will be doing a lot of repeated memory re-allocation.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!