Combining matrices from workspace or from directory into a single matrix.

10 views (last 30 days)
Can someone explain how to combine .mat files present in workspace or in directory into one .mat file? The problem is that the files are not properly named and the files have different rows but same number of coloumns.
  3 Comments
Sachin Patalasingh
Sachin Patalasingh on 17 Jul 2020
Thank you for the followup Arthur. I want to vertically concatenate matrices from workspace. There are 120 .mat files with different number of rows but same number of coloumns and they are named in a haphazard way.
David Hill
David Hill on 17 Jul 2020
If they are in the workspace, then they are already loaded. If they all have the same numbe of columns, then:
newMatrix=[a;b;c;d;e;f;g;h;i];%where a,b,c,d ... are your other maxtrics.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 17 Jul 2020
Edited: Stephen23 on 18 Jul 2020
Assuming that each .mat file contains exactly one array with compatible sizes:
D = 'path to the directory where the files are saved';
S = dir(fullfile(D,'*.mat'));
N = numel(S);
C = cell(1,N);
for k = 1:N
F = fullfile(D,S(k).name);
C(k) = struct2cell(load(F));
end
M = vertcat(C{:})
save('new.mat','M')
  3 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products


Release

R2015a

Community Treasure Hunt

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

Start Hunting!