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

M file in one location to loop over directories/sub directories in another location

Asked by Clifford Shelton on 25 Dec 2012

I'm not sure how to get this syntax to do exactly what i want it to do. Help is most appreciated!

I am trying to get my mfile to point to a different directory on my computer and loop over all the files in each subfolder. I can't get the syntax to work properly.

My M-file is located in C:/Users/Stuff

The Directory I want to point towards is: C:/Data and there are numerous subdirectories of this folder (C:/Data/041012, C:/Data/041112, C:/Data/041212.........etc.)

Here is the code I have so far that isn't working:

addpath(genpath('c:/data'))
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
%import
folder = 'c:\data';
   fileToRead1 = [Str{1} '.xls'];
   sheetName='Sheet1';
if exist(fileToRead1, 'file') == 0
  % File does not exist
  % Skip to bottom of loop and continue with the loop
  continue;
end   
% And then begin my calculations and functions here....

0 Comments

Clifford Shelton

Products

No products are associated with this question.

2 Answers

Answer by Walter Roberson on 25 Dec 2012

It is best not to use addpath()

folder = 'c:\data';
wantedfiles = {'Red' 'Orange' 'Yellow' 'Green' 'Blue' 'Indigo' 'Violet'};
subdirs = dir(folder);
subdirs(~[subdirs.isdir]) = [];    %eliminate non-directories
for K = 1 : length(subdirs)
  thissubdir = dirs(K).name;
  if strcmp(thissubdir, '.') || strcmp(thissubdir, '..'); continue; end
  subdirpath = [folder '\' thissubdir];
  for L = 1 : length(wantedfiles)
    fileToRead1 = fullfile( subdirpath, [wantedfiles{L} '.xls'] );
    if ~exist(fileToRead1, 'file'); continue; end
      ..... do your work ....
  end
end

0 Comments

Walter Roberson
Answer by Image Analyst on 25 Dec 2012

The genpath() function may be useful for you. It generates a list of all subfolders of a folder that you specify.

folderListCharArray = genpath('c:\Data');

folders will be separated by semicolons. I wish they'd have the option to return them individually in a cell array but they don't so you'll have to use regexp to split them apart.

0 Comments

Image Analyst

Contact us