Filter löschen
Filter löschen

subdirectories in a for loop

1 Ansicht (letzte 30 Tage)
Contoso Donoso
Contoso Donoso am 11 Mär. 2023
Kommentiert: Contoso Donoso am 13 Nov. 2023
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.

Akzeptierte Antwort

Stephen23
Stephen23 am 11 Mär. 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 Kommentar
Contoso Donoso
Contoso Donoso am 13 Nov. 2023
This was exaclty what I needed, thank you very much, and the natsortfiles function worked beautifuly, thanks a lot.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by