How to create a for loop through a directory for only certain folders in the directory
5 views (last 30 days)
Show older comments
Hi, I have a parent folder 'Sample'
In this folder, I have a lot of folders - some called sub01, sub02, etc. and others that have different names. I want to create an array of the paths for the subfolders in the parent folder that contain 'sub'. so that I can create a for loop through the array and apply it to each subfolder.
Thank you
0 Comments
Answers (2)
Sulaymon Eshkabilov
on 11 May 2019
In this case, path() should be the option to employ in order to have access to subfolders.
oldpath = path;
path('..\Sample\sub01',oldpath)
1 Comment
Stephen23
on 11 May 2019
Edited: Stephen23
on 11 May 2019
"In this case, path() should be the option to employ in order to have access to subfolders."
Changing the MATLAB Search Path is NOT an appropriate way to create a list of folder names, or to access data files or subfolders (it is slow, makes debugging more complex, and can have unintended side effects). The simpler and much more efficient solution is to use absolute/relative folder names (e.g. with dir and any file-import or -export functions).
In any case, this answer still does not create a list of folder names, as the question requested.
Stephen23
on 11 May 2019
Edited: Stephen23
on 11 May 2019
An efficient MATLAB solution:
P = 'absolute/relative path to the parent directory Sample';
S = dir(fullfile(P,'sub*'));
F = {S([S.isdir]).name};
N = numel(F)
for k = 1:N
T = fullfile(P,F{k})
...
end
If the subfolder names also include names like 'sub02old' which you want to exclude then you can do this by filtering N, e.g. using regular expressions or strncmp or the like.
0 Comments
See Also
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!