Kevin
Kevin

Reputation: 13

MATLAB string variables

I am attempting to write a function in MATLAB which will take a grouping of rather large excel files in a matrix to read and analyze the numbers (because there are a lot of excel files and a lot of numbers). I have the main function call a function which is supposed to take names of the excel files from the matrix in the main function and use the function 'xlsread' to read the appropriate cells. Each file has the same format and the same number of columns and rows, so designating the cells to read is not a problem. However, to pass each excel file to the read input function, I assign the name of the excel file to a variable, which is then passed to the read function, which then passes the variable into xlsread. However, when I run it, I get the error: "Filename must be a string." Below is an example of how I have my code set up.

filenames = {'file1.csv','file2.csv',....};
for i=1:10
   file=filenames(i);
   data=readin(file);
end


function [sheetdata] = readin(filename)
sheetdata = xlsread(filename,'cellrange','sheet');
end

Is this possible?

Just fyi, the xlsread function takes in arguments as strings. The first argument is the name of the file, such as:

'file1.xls'

The second argument is the range of cells to be imported, such as:

'B2:D5'

This tells MATLAB to import the data in the cells included in the rectangle with the upper left corner of B2 and a lower right corner of D5.

Thanks for any help.

EDIT: I can get it to work if I assign the variable directly to the file name, for example:

name='file1';
xlsread(name,'A1:C5');

So I guess the issue lies in how I am setting up the matrix of file names. I would like to set it up this way because I do not know how many sheets I will end up having to analyze, and by using a matrix, I can add, remove, or edit any of the sheets easily and quickly without having to change any other part of my code.

Upvotes: 1

Views: 551

Answers (1)

MrAzzaman
MrAzzaman

Reputation: 4768

Your problem is most likely with this line:

file=filenames(i);

filenames, as you've defined it, is a matrix of char. This means that filenames(1) will return f, not file1.csv as you intend. The best option, as I see it, is to convert filenames to a cell array:

filenames = {'file1.csv','file2.csv',....};
for i=1:10
   file=filenames{i};
   data=readin(file);
end

Upvotes: 5

Related Questions