subdirectories in a for loop

2 views (last 30 days)
I'm trying to run a foor loop that opens different subfolders from a main folder. The subfolders are named "Output1", "Output2", "Output3" and so on. I want to read a file with extension .mat that contatains many variables but I need the values of a specific variable and I need to store that in a vector.
I think I am missing something in my code.
% Set the directory to search in
folder_path = 'path/to/folder';
% Get a list of all the folders in the directory
contents=dir(folder_path);
results1=[]; %vector to append the needed values
for i = 1:numel(contents)
directory = ['F:/PhD/Swan pruebas/Iniciados/regreso/River/MorF Rs (Veg)/Output' num2str(i) '/'];
file_name = 'file.mat';
file_path = [directory file_name];
load(file_path);
z_i=value.z %the value that i need
results1=[results z_i];
end
So, from this I have two things that are not working as I expect. When I use contents it reads every file in the main folder (which are many), but I just want to read the folders that say Output and the corresponding number.
The other which is a big problem, is that the values that I am extrancting in each step of the loop are the same, so I am not sure if the code is not changing directories correctly and just reading the same file over and over, or if I'm missing a step, and I know I'm reading the same values on each step because I have plotted them each time step and are the exact same values each time. So I don't know what am I missing. Please help.
Hope I have made a clear explanation but if not, please let me know and I will try to further elaborate.

Accepted Answer

Stephen23
Stephen23 on 11 Mar 2023
P = 'F:/PhD/Swan pruebas/Iniciados/regreso/River/MorF Rs (Veg)';
S = dir(fullfile(P,'Output*','file.mat'));
S = natsortfiles(S); % must be downloaded: https://www.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort
for k = 1:numel(S)
F = fullfile(S(k).folder,S(k).name);
D = load(F, 'value');
S(k).data = D.value.z;
end
V = [S.data]
  1 Comment
Contoso Donoso
Contoso Donoso on 13 Nov 2023
This was exaclty what I needed, thank you very much, and the natsortfiles function worked beautifuly, thanks a lot.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!