How to end a loop with unknown length before it fails

2 views (last 30 days)
I'm trying to build a for end loop which will be used for thousands of different files each with different length. I get an error (Index exceeds matrix dimensions.) when the length of the loop is longer then the file itself.
I've been trying to implement a while / if statement but haven't succeeded. Anyone could advise?
if true
files = dir([datdir 'MV2*']);
for j=1:length(files)
fid = fopen([datdir files(j).name],'rt');
for p=1:10
tmp=fgetl(fid);
end
for i=1:500
for j=1:3
tmp=fgetl(fid);
end
ind=strfind(tmp,'LOCAL')
date=tmp(14:21)
time=tmp(23:28)
t=[t;datenum(date,'yyyymmdd')+datenum(time,'HHMMSS')-734869];
for j=1:3
tmp=fgetl(fid);
end
C=textscan(fid,'%f %f');
ssc=[ssc;mean(C{2})];
end
fclose(fid);
end
% code
end
The error comes from the line with date=tmp(14:21). (so also time=tmp(23:28)
Probably i could manage myself if someone could tell me where i should implement the while statement.
Thanks a lot in advance! :)
  2 Comments
Adam
Adam on 28 Feb 2015
It is hard to recommend something without understanding your files. Your code suggests you expect your files to have a format that includes the date and time at those specified locations. If that is the case then there is a problem with one of your files, if it isn't the case you need more clauses around your code that makes these expectations.
e.g.
if numel( tmp ) >= 21
date = tmp(14:21);
end
Yuri Engelshoven
Yuri Engelshoven on 28 Feb 2015
The problem is that the file wants to continue doing loops although there is no more data left in the file. All the files are formatted exactly the same only thing is that some are 100 lines and some up to 1500.
A file is included.

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 28 Feb 2015
Don't use date as the name of a variable - it's already the name of a built-in function.
Why not put a breakpoint at that line and see what tmp is? I bet it's not what you were expecting.
Also, next time put the complete error message (ALL the red text), not just a small part snipped out of it.
  4 Comments
Yuri Engelshoven
Yuri Engelshoven on 28 Feb 2015
Thanks a lot! Just by adding that exact piece of coding the problem was solved!
Image Analyst
Image Analyst on 28 Feb 2015
You're welcome. Can you then officially mark the Answer as "Accepted" and vote for it?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!