how do I merge multiple matrices into one?
Show older comments
I have 50 1111 x 3 size matrics. I want to combine them into one final matrix such as all first rows from individual matrices are in first 50 rows and then all 2nd rows and so on. Also, for each set of rows it should insert a header row at the beginning.
How do I do this in Matlab?
5 Comments
James Tursa
on 25 Feb 2021
How are these 50 variables stored in MATLAB currently? As separately named variables? How do you get them into the workspace?
Shirish Kulkarni
on 25 Feb 2021
Bob Thompson
on 25 Feb 2021
Edited: Bob Thompson
on 25 Feb 2021
How are you creating the variables?
The only 'good' way of combining 50 unique variables (as far as I know) is manually, but it might be possible to index the results when you first make them so they don't need to be individual variables.
Walter Roberson
on 25 Feb 2021
Is this for writing into an xlsx file? SInce you cannot create a numeric array that has header rows in the middle of it, and if you were to create a table() object all of the entries would have to be cells in order to permit the header rows to be in middle of it.
Shirish Kulkarni
on 26 Feb 2021
Answers (1)
One approach
N = 4; %50 in your original
Rows = 2; %1111 in your original
%generate some data for illustration
M = arrayfun(@(ignore) randi(9,Rows,3), (1:N).', 'uniform', 0)
cell2mat(M) %for illustration
nrow = size(M{1},1);
headers = repmat(-(1:nrow).', 1, 3);
grouped = arrayfun(@(row) cell2mat(cellfun(@(C) C(row,:), M, 'uniform', 0)), 1:nrow, 'uniform', 0)
headered = [num2cell(headers,2).'; grouped]
joint = cell2mat(headered(:))
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!