MATLAB Answers


Error importing files in a ForLoop

Asked by Clifford Shelton on 13 Dec 2012

I keep running into an error when I try to run this code..but I am unsure why.

I am trying to import files within a for loop for each baseball team.

I think the problem is I am not setting my variable correctly..but I am totally confused as to how/what is what wrong with this code. Help most appreciated!

Most of this code was auto generated after manually importing a file.

I am getting my error at the line:


??? Error using ==> xlsread at 122 Filename must be a string.

Error in ==> importhome at 10 [numbers, strings, raw] = xlsread(fileToRead1, sheetName);

Error in ==> baseball2 at 10 importhome(fileToRead1)

Here is my Code:

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 '.xls'];
% Call the first function.
%  Imports data from the specified file
%  FILETOREAD1:  file to read
%  Auto-generated by MATLAB on 05-May-2012 23:12:52
% Import the file
[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));



No products are associated with this question.

1 Answer

Answer by John Petersen
on 13 Dec 2012

You are not indexing Str. Replace the first half of your program with

Str = {...};  % your teams
for i=1:length(Str)
   folder = '';
   fileToRead1 = [Str{i} '.xls'];
   [numbers, strings, raw] = xlsread(fileToRead1, sheetName);
   ... % rest of your program


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!