dpb
Posts:
6,677
Registered:
6/7/07
|
|
Re: break a loop when reading different excel files
Posted:
Nov 26, 2012 10:28 AM
|
|
On 11/26/2012 8:31 AM, Saad wrote: > 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
Several ways...
a) enclose the call to xlsread() in a try...catch error block and handle the error
b) do a dir() on the file name before try to open to test for existence and break if not found,
c) use dir() on the file name w/ appropriate wild card and the process the resulting files so only have existing files to deal with instead. Has secondary benefit of not needing the sprintf() stuff to create the filename manually..
--
|
|