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

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

I'm not sure about what you want : do you need to merge MAT-File or to concatenate matrix with different size ? What is your original purpose ?
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.
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

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

I think you typed a comma in place of a dot in S = dir(fullfile(D,'*,mat'));
S = dir(fullfile(D,'*.mat')); %rectified one
@Sachin Patalasingh: you are right, I fixed the answer. Thank you!
Thank you for solving the problem, Stephen.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2015a

Community Treasure Hunt

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

Start Hunting!