MATLAB Answers


Continue in a for loop if a file isn't present

Asked by Clifford Shelton on 22 Dec 2012

I'm having a problem with the correct syntax to complete the task without receiving an error. Any help is most appreciated!

In my program there is a for loop to import a series of spreadsheets into Matlab. These spreadsheets are for every US baseball team.

I want to know the syntax of how to skip and continue the for loop if one of the files within the loop are not found in the folder.

Here is the code i have so far:

for Str = {'Diamondbacks' 'Braves' 'Orioles' 'Boston' 'Cubs' 'WhiteSox' 'Reds' 'Indians' 'Rockies' 'Tigers' 'Astros' 'Royals' 'Angels' 'Dodgers' 'Marlins' 'Brewers' 'Twins' 'Mets' 'Yankees' 'Athletics' 'Phillies' 'Pirates' 'Padres' 'Giants' 'Mariners' 'Cardinals' 'Rays' 'Rangers' 'BlueJays' 'Nationals'};
folder = '';
   fileToRead1 = [Str{1} '.xls'];
 // this is to organize the data in a way easy for me to use 
     [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, :);
// Here is my feeble attempt to skip and continue the forloop if a file is
// not found.  It doesn't work of course.  
if ~isempty(fileToRead1) =  numbers;



No products are associated with this question.

1 Answer

Answer by Image Analyst
on 22 Dec 2012
Edited by Image Analyst
on 22 Dec 2012
 Accepted answer

Continue if the file is not there:

if exist(fileToRead1, 'file') == 0
  % File does not exist
  % Skip to bottom of loop and continue with the loop


I also tried:

if exists(fileToRead1, [Str{1} '.xls']) == 0
  % File does not exist
  % Skip to bottom of loop and continue with the loop

And got the same error. Not sure what I'm doing wrong.

Use exist() instead of exists().

I make that mistake a lot myself!

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!