Break a loop when reading different excel files
1 view (last 30 days)
Show older comments
Dear all,
I am trying to read different excel files from 2010 to 2012. Basically, for each month, there is one excel file. So when i run the loop I go through each month and read the excel file of that particular. The loop works with no problem for 2010 and 2011 but it stops at the end of 2012 because the data for November and December 2012 are not available yet. Here is my code:
months={'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'};
for i=2010:2012
for j=1:length(months)
a1=xlsread(['P:\X\Data\', num2str(i),'\', char(months(j)), num2str(i), '.xls'],'Sheet1','X5:X5000');
end
end
As you can see the loop reads the excel file at each month but stops at end 2012. I would like to end (break) the loop when Matlab doesnt find the relevant excel file. How can I do that? Thank you very much for your help
Kind REgards
S
0 Comments
Answers (1)
Image Analyst
on 26 Nov 2012
Edited: Image Analyst
on 26 Nov 2012
It's more robust if you don't break and just check for existence and let it finish the loop. For example, what if all the files are there except the February file? If you broke out, you'd never process the March file or any files in subsequent years. It doesn't take long at all to check filenames for existence. If you want, you could also call warndlg() if there is a missing file. And a1 gets overwritten on each iteration in your loop, so I assume that there's some processing that goes on in the loop that you didn't show.
Try it this way, using braces instead of char(), and using exist(), sprintf(), and fullfile():
months={'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'};
for theYear = 2010:2012
for theMonth=1:length(months)
baseFileName = sprintf('%s%d.xls', months{theMonth}, theYear);
fullFileName = fullfile('P:\X\Data\', num2str(theYear), baseFileName)
if exist(fullFileName, 'file')
a1 = xlsread(fullFileName, 'Sheet1', 'X5:X5000');
end
end
end
See Also
Categories
Find more on Environment and Settings 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!