MATLAB: How to adapt a script to go through different subfolders

folders subfolders

I've made a script for checking a folder for files with a size smaller than 100kb. It works when I use it for one folder, however, I now need it to work for a folder with several subfolders.
my original script looks like this
myFolder = 'C:\';
filePattern = fullfile(myFolder,'*.jpg');
theFiles = dir(filePattern);
for k = 1 : length(theFiles) %first see if there are images with size <10kb
a = [theFiles.bytes];
baseFileName = theFiles(k).name;
sizeFileName = theFiles(k).bytes;
fullFileName = fullfile(myFolder, baseFileName, sizeFileName);
if a(k) < 100e3 % 10kb

fprintf('\n%s: picture to delete',fullFileName);
end
end
a = [theFiles.bytes];
b = (a < 100e3);
c = a(b);
if numel(c)> 1
delete(fullfile(theFiles(k).folder, theFiles(k).name));
fprintf('\n%s: deleted', fullFileName);
else
fprintf('\n only one small picture in folder', baseFileName);
end
my effort to make the script go through multiple subfolders:
myFolder = 'C:\';
S = dir(fullfile(myFolder,'*'));
N = setdiff({S([S.isdir]).name},{'.','..'}); % list of subfolders of myFolder.
for ii = 1:numel(N)
theFiles = dir(fullfile(myFolder,N{ii},'*jpg'));
C = {theFiles(~[theFiles.isdir]).name}; % files in subfolder.
for jj = 1:numel(theFiles)
F = fullfile(myFolder,N{ii},C{jj});
a = [theFiles.bytes];
baseFileName = theFiles(jj).name;
sizeFileName = theFiles(jj).bytes;
fullFileName = fullfile(myFolder, baseFileName, sizeFileName);
if a(jj) < 100e3 % 10kb
fprintf('\n%s: picture to delete',fullFileName);
end
end %until this part the script works fine
b = (a < 100e3);
c = a(b);
if numel(c)> 1
delete(fullfile(theFiles(jj).folder, theFiles(jj).name));
fprintf('\n%s: deleted', fullFileName);
else
fprintf('\n only one small picture in folder', baseFileName);
end
end
The first part of the script works fine, however, in the second part it looks like it keeps on looping without actually doing anything.
Thanks in advance

Best Answer

Both of your loops suffer the same problem: you delete only the last file. This is because after the loop you use the loop iteration variable as an index to obtain the filename, but at that point the loop iteration index is whatever it was on the last loop iteration.
You would need to loop over the indices corresponding to the files which match your logical comparison, e.g.:
D = 'C:\';
S = dir(fullfile(D,'*.jpg'));
B = [S.bytes];
X = B < 100e3;
C = {S(X).name};
fprintf('picture to delete: %s\n',C{:});
for jj = 2:numel(C) % apply your own logic here
delete(fullfile(D,C{jj}))
end