Using a loop to load multiple mat files from measurement into the workspace

1 view (last 30 days)
Hello everyone,
it is my first time here.
My goal is to load a specific information out of around 20188 mat-files. Each file is a measurement-point. Each file includes two types of Informations. It is the surface and width of a area. I m only interested in the width. In the first picture you can see a Overview over the first five mat-files as the first five measurement points.The second picture here shows the structure of the first of the 20188 mat-files. In the picture the germen language is used. (width=max_Breite and surface=Flaeche, Measurement=Messung)
My code is here. The programm should write the parameter max_Breite in the array width. But because of the Ending .max_Breite he can't find the file.
width=[0];
for i=1:20188
switch i
case i<=9
width(i)=load(sprintf('Messung_0000%d.mat.max_Breite',i));
case i>=10 && i<100
width(i)=load(sprintf('Messung_000%d.mat.max_Breite',i));
case i>=100 && i<1000
width(i)=load(sprintf('Messung_00%d.mat.max_Breite',i));
case i>=1000 && i<10000
width(i)=load(sprintf('Messung_0%d.mat.max_Breite',i));
otherwise
width(i)=load(sprintf('Messung_%d.mat.max_Breite',i));
end
end
Error:
Error using load
Unable to read file 'Messung_00001.mat.max_Breite'. No such file or directory.
Error in Daten (line 22)
width(i)=load(sprintf('Messung_0000%d.mat.max_Breite',i));
Does somebody have a idear. I appreciate every kind of help and i m thankfull for everything. If you want you can write in german.
I thank you in advance
Erik
  2 Comments
Erik
Erik on 4 Sep 2022
thank you very much, you helped me to improve my code. You are right, i deleted my initialization of the array width. With out the ending .max_Breite i could merge all files to one.

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 3 Sep 2022
Edited: Stephen23 on 3 Sep 2022
P = '.'; % absolute or relative path to where the files are saved
S = dir(fullfile(P,'Messung_*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
D = load(F);
S(k).width = D.max_Breite;
end
all_widths = vertcat(S.width)
The filenames and MAX_BREITE are stored in the structure array S. For example, the second file:
S(2).name
S(2).width

Categories

Find more on Files and Folders 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!