The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: break a loop when reading different excel files
Replies: 2   Last Post: Nov 26, 2012 1:29 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]

Posts: 9,850
Registered: 6/7/07
Re: break a loop when reading different excel files
Posted: Nov 26, 2012 10:28 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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..


Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.