How do I use xlsread in a for loop?

8 views (last 30 days)
Hello, I've read several responses on this site vaguely related to my question, but I'm a pretty new user so they didn't really help me much. All I'm trying to do is to get Matlab to take some .xlsx files and assign them to matrices. There are 14 files in my specified folder (the same one the matlab code is running in) and they are named File1.xlsx - File14.xlsx. So far, I've failed miserably to get matlab to even recognize that these files exist when I run xlsread within a simple for loop. I figured I'd worry about the matrix assignments later, yes I know this will just reassign this to matrix over and over. Here's my code so far.
for i = 1:14
bob = strcat('File',i,'.xlsx')
matrix = xlsread(bob);
end
With output:
Error using xlsread (line 128)
XLSREAD unable to open file 'File.xlsx'.
File '/Users/timmoreno/Desktop/KLH Data Formatted/File.xlsx' not found.
Error in ReadTest1 (line 6)
matrix = xlsread(bob);
Notice that it completely ignores that i = 1, but even if I put in strcat('File1',i,'.xlsx') it still fails to see the file, which is there, and works if I use xlsread on File1 outside of a for loop. What the heck is happening?
I'm grateful for any help, I should also mention that I'm running Matlab 2015.

Accepted Answer

Star Strider
Star Strider on 17 Aug 2015
There are several ways to do what you want, one is:
bob = sprintf('File%d.xlsx',i);
It depends on how your files are named. If the numbers include leading zeros, consider:
bob = sprintf('File%02d.xlsx',i);
or something similar.
  3 Comments
Joseph Porter
Joseph Porter on 23 Apr 2017
I need to do this for sheet numbers within my xls read. my code is the same as OP but the solution doesn't work,I can only assume as sheet number is a string within '' markers. any thoughts how to loop sheet number in xlsread? thank you

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!