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

10 ビュー (過去 30 日間)
Naomi Gaggi
Naomi Gaggi 2019 年 5 月 10 日
編集済み: Stephen23 2019 年 5 月 11 日
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

回答 (2 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019 年 5 月 11 日
In this case, path() should be the option to employ in order to have access to subfolders.
oldpath = path;
path('..\Sample\sub01',oldpath)
  1 件のコメント
Stephen23
Stephen23 2019 年 5 月 11 日
編集済み: Stephen23 2019 年 5 月 11 日
"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
Stephen23 2019 年 5 月 11 日
編集済み: Stephen23 2019 年 5 月 11 日
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.

カテゴリ

Help Center および File ExchangeSearch Path についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by