How to go through multiple subfolders for operation?

1 次查看(过去 30 天)
I only can access into one folder and process the data inside that folder. My Code is like this
%Specifying file directory for Ignition delay time
IGNfolder = '/home/ali//Curve_Matching_vs_Moments/IDT/test/Test_rig';
% It checks whether the folder actually exists or not. Warning message to the user if not.
if ~isdir(IGNfolder)
errorMessage = sprintf('Error: The following folder is not found:\n%s', IGNfolder);
uiwait(warndlg(errorMessage));
return;
end
% To get all the files in that directory and with desired file name pattern.
Allfiles = dir(fullfile(IGNfolder, '*.txt'));
allData = [];
for k = 1:length(Allfiles)
initialFileName = Allfiles(k).name;
fullFileName = fullfile(IGNfolder, initialFileName);
.
.
.
end
If i have multiple such kind of folder (Test_rig), How can i access into them one after another ?
For better explaining if i have one folder named 'JSR' which contains subfolders name " '1', '2', '3', '4'......................., 'n' " .
N.B: There are other subfolders also, but i only need to access into subfolders named " '1', '2', '3', '4'......................., 'n' " .

采纳的回答

Stephen23
Stephen23 2018-11-19
编辑:Stephen23 2021-4-26
"For better explaining if i have one folder named 'JSR' which contains subfolders name '1', '2', '3', '4'......................., 'n' "
P = 'path to directory JSR';
S = dir(fullfile(P,'*'))
X = [S.isdir] & ~cellfun('isempty',regexp({S.name},'^\d+$','once'));
S = natsortfiles(S(X)); % optional: download from FEX.
for k = 1:numel(S)
F = fullfile(P,S(k).name) % path to subdirectory.
... your code
end
You can download natsortfiles here:
  3 个评论
Stephen23
Stephen23 2018-11-19
编辑:Stephen23 2021-4-26
"It would great help, if you edit my code. "
Your code does not mention any folder with the name '1', '2', etc., so it is not clear how your code relates to your actual question, or my answer. Also I used dir to identify the subfolder names, so isdir is totally superfluous. Only you can decide if this is suitable for your workflow.
Perhaps this is what you want:
P = 'path to directory JSR';
S = dir(fullfile(P,'*'))
X = [S.isdir] & ~cellfun('isempty',regexp({S.name},'^\d+$','once'));
S = natsortfiles(S(X)); % optional: download from FEX.
for ii = 1:numel(S) % loop over each subfolder.
T = dir(fullfile(P,S(ii).name,'*.txt'));
for jj = 1:numel(T) % loop over each file.
F = fullfile(P,S(ii).name,T(jj).name);
... code processing file F.
end
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by