Clear Filters
Clear Filters

How to go through multiple subfolders for operation?

5 views (last 30 days)
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' " .

Accepted Answer

Stephen23
Stephen23 on 19 Nov 2018
Edited: Stephen23 on 26 Apr 2021
"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 Comments
Stephen23
Stephen23 on 19 Nov 2018
Edited: Stephen23 on 26 Apr 2021
"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
Mr. 206
Mr. 206 on 19 Nov 2018
Thank you very much.
That is what i wanted.
Great!!

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!