MATLAB Answers


Loop over files within a directory and all its sub-directories

Asked by Clifford Shelton on 24 Dec 2012
Latest activity Commented on by Walter Roberson
on 16 Sep 2016

Happy Holidays to everyone!

I have a folder: C:\data

and I wish to loop over all the files that are within the sub-folders that are named by dates in a MMDDYY fashion (example 122312, 122412, 122512...etc.)

The filenames of the files within each subfolder are all associated with the names of the strings in my array. (see sample code below)

After doing some research I'm not sure which function is best for my needs..nor do I know the proper syntax to utilize them without error. (I tried genpath, or numel with no success)

Any help is appreciated. Here is some example code:

%my FEEBLE attempt to begin to loop through the specified folder and all its sub-directories
for f = 1 : numel('files')
% The names of the files I will be analyzing
for Str = {'Red' 'Orange' 'Yellow' 'Green' 'Blue' 'Indigo' 'Violet'};
%I don't think this next line of code is right.  But i'm trying to apply the names of each associated color with the name of the file to
folder = 'c:\data';
   fileToRead1 = [Str{1} '.xls'];
if exist(fileToRead1, 'file') == 0
  % File does not exist
  % Skip to bottom of loop and continue with the loop
% And then begin my calculations and functions here....

Thank you in advance! Ho Ho Ho!



No products are associated with this question.

2 Answers

Answer by Walter Roberson
on 24 Dec 2012


on 16 Sep 2016

this solution only looks for files within a single folder, not recursive on subfolders

Depth first or breadth first?

Answer by Jan Simon
on 16 Sep 2016


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!