subdirectories in a for loop

1 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2023-3-11
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 个评论
Contoso Donoso
Contoso Donoso 2023-11-13
This was exaclty what I needed, thank you very much, and the natsortfiles function worked beautifuly, thanks a lot.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by