필터 지우기
필터 지우기

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 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