フィルターのクリア

subdirectories in a for loop

1 回表示 (過去 30 日間)
Contoso Donoso
Contoso Donoso 2023 年 3 月 11 日
コメント済み: Contoso Donoso 2023 年 11 月 13 日
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 Center および File ExchangeLoops 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