How can i load .mat files from subfolders with for loop?
Show older comments
I have a different number of .mat files in several folders, which I would like to import, plot data und save it in the same folder as a pdf file.
Here an example with two folders:
C:\Users\I2d1_4_1_1\
y3.mat
y4.mat
y5.mat
C:\Users\I5d1_4_1_1\
y3.mat
y4.mat
y5.mat
y6.mat
My two questions are:
- How do i save it in the same folder without changing the directory.
- How to adapt the code that i dont need to change the for loop i=3:5 for the first folder and i=3:6 for the second folder.
DataPath ='C:\Users\';
for i=3:60
for input=[2 5 8]
for delay=[4 8 12];
for delayinput=[1 4 8];
load([DataPath 'I%dd1_%d_1_%d\y' num2str(i) '.mat',input,delay,delayinput])
figure(1), plotregression(x, y);
SaveName = sprintf('NN_%d_1_%d',i,delay);
saveas(figure(1),fullfile(DataPath 'I%dd1_%d_1_%d', SaveName),'pdf')
end
end
end
end
Thanks for your help.
Accepted Answer
More Answers (1)
Akira Agata
on 3 Dec 2019
How about using dir function?
Using the function, the solution would be like this:
fileList = dir('C:\Users\**\*.mat');
for kk = 1:numel(fileList)
filePath = fullfile(fileList(kk).folder,fileList(kk).name);
load(filePath);
h = figure;
plotregression(x,y);
saveName = replace(fileList(kk).name,'.mat','.pdf');
saveas(h,fullfile(fileList(kk).folder,saveName));
close(h);
end
6 Comments
Josef Bubendorfer
on 3 Dec 2019
Akira Agata
on 3 Dec 2019
OK, then you can skip unwanted .mat files by simply adding if statement.
For example, if you want to save in .pdf for only y1~y6.mat, the program would be like this:
fileList = dir('C:\Users\**\*.mat');
for kk = 1:numel(fileList)
if ~isempty(regexp(fileList(kk).name,'y[1-6].mat'))
filePath = fullfile(fileList(kk).folder,fileList(kk).name);
load(filePath);
h = figure;
plotregression(x,y);
saveName = replace(fileList(kk).name,'.mat','.pdf');
saveas(h,fullfile(fileList(kk).folder,saveName));
close(h);
end
end
Image Analyst
on 3 Dec 2019
Or, for any y*.mat but not other files beginning with a different letter:
fileList = dir('C:\Users\**\y*.mat');
And then skip the "if" inside the "for".
You might also want to take a look at fileDatastore().
Josef Bubendorfer
on 3 Dec 2019
Akira Agata
on 3 Dec 2019
Then, you should change the first line to:
fileList = dir('C:\Users\I2d1_4_1_1\*.mat');
and change the fileList(kk).folder to 'C:\Users\I2d1_4_1_1\'.
Then, please do the same thing to the other folder C:\Users\I5d1_4_1_1\.
Josef Bubendorfer
on 4 Dec 2019
Categories
Find more on Variables 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!