MATLAB Answers


How to loop through all files in subfolders in a main folder?

I have a main folder and several subfolders in it. Each subfolder has several files within them. I want to create a loop in such a manner that the code would open a subfolder, do what I want it to do and then move to the next one.
Thanks in advance


Sign in to comment.

1 Answer

Answer by Stephen Cobeldick on 28 Dec 2018
Edited by Stephen Cobeldick on 28 Dec 2018
 Accepted Answer

D = 'full path to the main folder';
S = dir(fullfile(D,'*'));
N = setdiff({S([S.isdir]).name},{'.','..'}); % list of subfolders of D.
for ii = 1:numel(N)
T = dir(fullfile(D,N{ii},'*')); % improve by specifying the file extension.
C = {T(~[T.isdir]).name}; % files in subfolder.
for jj = 1:numel(C)
F = fullfile(D,N{ii},C{jj})
% do whatever with file F.


Thanks a million. I have had a look at several answers, but this was the easiest one. The code worked perfectly as I desired.
I was using files with extension .zfr in different sub folders. I used this loop to convert those files to .txt. Thank you

Sign in to comment.