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

Looping through A Folder and all its subdirectories.....Happy New Year!!

Asked by Clifford Shelton on 31 Dec 2012

Ok. Many trouble shooting hours ...and many error "dings" later, I'm still having the same problem. Due to my beginner skills I'm having problems achieving the following segment of my project:

I will be as detailed as possible so I can hopefully nail it this time:

- On my computer i have a folder C:\data which contains many different subfolders.

- The subfolders are named by dates in a MMDDYY fashion. For example "040312"

- In each subfolder are excel files named after Baseball teams. each subfolder may contain a different combination of xls files.

I am trying to write code that achieves the following objectives:

1.) Loops through all the subfolders of the C:\data folder looking for xls files that have the filenames: Angles.xls, Diamondbacks.xls, etc.

2.) If the files are found in each subfolder import the spreadsheet data and generate a plot of the data titled "Score" and "Allow".

3.) If the file is not found any given subfolder skip and continue to the next file to be located. 4.)Then save the generated plot in the same folder that the spreadsheet was imported from as a .fig and a .bmp file.

I've gotten hints to use various functions like: genpath, dir, but the code I've been fumbling through isn't able to achieve my goals.

a) the script doesn't import the excel files from all the subfolders

b) the script wont save the .fig or .bmp file in the associated subfolder

Here is the code I have been fumbling through:

%I know all of this is wrong wrong wrong.  Please help to adjust my code to %achieve the objectives outlined above!
  folder = 'c:\data';
  subdirs = dir(folder);
  subdirs(~[subdirs.isdir]) = [] ; 
  numberOfFolders = length(subdirs);
  if numberOfFolders <= 0
      uiwait(warndlg('Number of folders = 0!'))
  wantedfiles = {'Angels' 'Diamondbacks' 'Orioles' 'Royals' 'Yankees' 'Mets' 'Giants'};
    for K = 1 : numberOfFolders
      thissubdir = subdirs(K).name;
    if strcmp(thissubdir, '.') || strcmp(thissubdir, '..')
      subdirpath = [folder '\' thissubdir];
    for L = 1 : length(wantedfiles)  
    for wantedfiles = {'Angels' 'Diamondbacks' 'Orioles' 'Royals' 'Yankees' 'Mets' 'Giants'};
    folder = '';
       fileToRead1 = [wantedfiles{1} '.xls'];
    if exist(fileToRead1, 'file') == 0
      % File does not exist
      % Skip to bottom of loop and continue with the loop
%This is to import the data and organize it
% All of this code I had auto-generated from importing files manually
     [numbers, strings, raw] = xlsread(fileToRead1, sheetName);
  if ~isempty(numbers) =  numbers;
    if ~isempty(strings) && ~isempty(numbers)
        [strRows, strCols] = size(strings);
        [numRows, numCols] = size(numbers);
        likelyRow = size(raw,1) - numRows;
        % Break the data up into a new structure with one field per column.
        if strCols == numCols && likelyRow > 0 && strRows >= likelyRow
            newData1.colheaders = strings(likelyRow, :);
    % Create new variables in the base workspace from those fields.
    for i = 1:size(newData1.colheaders, 2)
        assignin('base', genvarname(newData1.colheaders{i}),,i));
    % Now I execute the plotting of data
    subplot (2,1,1), plot(Score,Allow)
    title([wantedfiles{1} 'Testing to see if it works']);
    subplot (2,1,2), plot(Allow,Score)
    title('Well, did it?');
  % here I save the generated plots, but they don't save where I want them to
    saveas(gcf,[wantedfiles{1} ' did it work.fig']);
    saveas(gcf,[wantedfiles{1} ' did it work.bmp']);
%At the end of the script I still was unable to loop over the files that I wanted


Matt J on 31 Dec 2012

Did you check whether exist(fileToRead1, 'file') is returning true or false? It appears that it might be returning false? Are you sure the file does exist?

Did you use the path() command to check whether its directory was successfully put on the path by addpath(genpath('c:\data'))?

Incidentally, now that you've told us that the same file names are reused in different directories, the genpath approach doesn't seem applicable anymore. You need to distinguish between the different versions of Diamondbacks.xls based on their subdirpath. I notice that your code computes subdirpath, but never uses it in the import step.

Clifford Shelton on 31 Dec 2012

"I notice that your code computes subdirpath, but never uses it in the import step."

Ah ha! That definitely is a problem. After reading around a bit it seems that uipickfiles() is suggested. But I want to have this process automated so that doesn't sound like the path I should take.

Am I on the right track here?:

for wantedfiles = {'Angels' 'Diamondbacks' 'Orioles' 'Royals' 'Yankees' 'Mets' 'Giants'};
folder = [subdirs(K).name];
   fileToRead1 = [wantedfiles{1} '.xls'];
if exist(fileToRead1, 'file') == 0
  % File does not exist
  % Skip to bottom of loop and continue with the loop

While debugging the code above in my for loop I am unable to advance to the next folder in my 'subdir' path. The loop just repeats over the first folder again. I'm not sure whey that is.

THanks for the help!!

Clifford Shelton on 31 Dec 2012

I didn't see that comment below before I responded. Let me play around with that suggestion. Sorry! And Thanks both to you and Walter!

Clifford Shelton


No products are associated with this question.

1 Answer

Answer by Walter Roberson on 31 Dec 2012
   fileToRead1 = fullfile(subdirpath, [wantedfiles{1} '.xls']);


Walter Roberson

Contact us