How to create a for loop through a directory for only certain folders in the directory

6 visualizzazioni (ultimi 30 giorni)
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
Sulaymon Eshkabilov il 11 Mag 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 Commento
Stephen23
Stephen23 il 11 Mag 2019
Modificato: Stephen23 il 11 Mag 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.

Accedi per commentare.


Stephen23
Stephen23 il 11 Mag 2019
Modificato: Stephen23 il 11 Mag 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.

Categorie

Scopri di più su File Operations in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by