MATLAB Answers

0

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

Asked by Naomi Gaggi on 10 May 2019
Latest activity Edited by Stephen Cobeldick on 11 May 2019
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

Sign in to comment.

Tags

2 Answers

Answer by 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

"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.

Sign in to comment.


Answer by Stephen Cobeldick on 11 May 2019
Edited by Stephen Cobeldick 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

Sign in to comment.