How to create a for loop through a directory for only certain folders in the directory
Mostra commenti meno recenti
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
Risposte (2)
Sulaymon Eshkabilov
il 11 Mag 2019
0 voti
In this case, path() should be the option to employ in order to have access to subfolders.
oldpath = path;
path('..\Sample\sub01',oldpath)
1 Commento
"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.
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.
Categorie
Scopri di più su File Operations in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!