MATLAB: Can you use DIR to list files in subfolders

dir

Hello,
Would somebody be able to advise me on how to use DIR to find the dates that each file was last modified with a .mat extension in all sub folders in current directory?
This code does not look in sub directories. Also how to you specify the .mat extension.
files = dir(datenum)
Many thanks

Best Answer

You cannot do that in a single dir() call.
You need one dir() call on the current folder, and you look at the isdir() field of the results to see which names correspond to folders:
dirinfo = dir();
dirinfo(~[dirinfo.isdir]) = []; %remove non-directories
Then do a step to remove the folder names "." and ".." so you do not infinite loop.
Then you loop over all those names and look inside each of the designated folders:
subdirinfo = cell(length(dirinfo));
for K = 1 : length(dirinfo)
thisdir = dirinfo(K).name;
subdirinfo{K} = dir(fullfile(thisdir, '*.mat'));
end
Now subdirinfo{K} is the structure of information about the .mat files in the directory dirinfo(K).name