Break a loop when reading different excel files

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

답변 (1개)

Image Analyst
Image Analyst 2012년 11월 26일
편집: Image Analyst 2012년 11월 26일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2012년 11월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by