MATLAB: How to create a loop that runs a function and save output through subfolders in a directory

folderssave

I am able to run my code only from here C:\Users\39218\Desktop\PROJECT\TD\P2\S6.
Then I have to move in P2S#….then P13S# (there is no a sequential order in the name)
My code computes 4 matrices (indeed there is also a plot where there are all subplots together) and save the output in the current folder.
What I want is to run my code from C:\Users\39218\Desktop\PROJECT. Furthermore, the code has to save those 4 matrices and the big plot for each one S# in a new folder (empty) with the associate name P#S#
FolderStructure= dir ('*.c3d'); %start from folder PM
con= struct2cell(FolderStructure);
myFiles =con(1,:)'
Phases_I=[];
Phases_O=[];
GR_I=[];
GR_O=[];
for z =1:length(myFiles)
name = string(myFiles(z))
% do something
Phases_I=[Phases_I; Times_Tot_I]
Phases_O=[Phases_O; Times_Tot_O]
GR_I=[GR_I;GR_Tot_I]
GR_O=[GR_O;GR_Tot_O]
end
% subplot
save('Phases_I.mat','Phases_I')
save('Phases_O.mat','Phases_O')
save('GR_I.mat','GR_I')
save('GR_O.mat','GR_O')

Best Answer

I replicated your file structure as I understood your explanation, it looks like this:
Obviously I do not have your data files, so I just filled the S# folders with a few CSV files to test this code with. You will need to adapt the code to suit your exact needs and file structure! Also note that if you want the files imported in alphanumeric order then one solution is to download my FEX submission natsortfiles and replace all of the instances of
setdiff(...)
with
natsortfiles(setdiff(...))
Note that the data Phases_I, etc. are collected into the non-scalar structure S3:
All folders with names starting with P or S located in the relevant subdirectories are processed.
D = 'C:\Users\stephen.cobeldick\Desktop\Project\TD';
S1 = dir(fullfile(D,'P*'));
C1 = setdiff({S1([S1.isdir]).name},{'.','..'});
for k1 = 1:numel(C1) % loop over P# directories
S2 = dir(fullfile(D,C1{k1},'S*'));
C2 = setdiff({S2([S2.isdir]).name},{'.','..'});
for k2 = 1:numel(C2) % loop over S# directories
S3 = dir(fullfile(D,C1{k1},C2{k2},'*.c3d'));
for k3 = 1:numel(S3) % loop over files
F = fullfile(D,C1{k1},C2{k2},S3(k3).name);
M = csvread(F);
... do whatever with your data
% S3(k3).Phases_I = Times_Tot_I;
% S3(k3).Phases_O = Times_Tot_O;
% S3(k3).GR_I = GR_Tot_I;
% S3(k3).GR_O = GR_Tot_O;
end
% Phases_I = vertcat(S3.Phases_I); % See note about NATSORTFILES and file order!
% Phases_I = vertcat(S3.Phases_O);
% GR_I = vertcat(S3.GR_I);
% GR_I = vertcat(S3.GR_O);
% do whatver with those variables...
% plot, save, etc.
% Make new subdirectory:
new = fullfile(D,[C1{k1},C2{k2}]);
mkdir(new)
% saveas(fgh,fullfile(new,'image.png'))
end
end