file data error reading

2 views (last 30 days)
Morteza
Morteza on 17 Jun 2014
Answered: Geoff Hayes on 17 Jun 2014
I have this dataset in a txt file.
25 0.109 1
corrupted line
20 0.096 2
100 0 3
15 0.517 3
15 0.8 5
35 1.086 4
3
40 0.934 2
3 3 3 3 3 3
35 0.109 1
22 0.100 1
21 0.100 2
16 0.600 3
17 0.850 5
32 1.080 4
45 0.950 2
37 0.110 1
I want MATLAB to read the data and skip the lines where there are errors (like line 2 and 8) and then explain in which line the error occured and what error was.
I just dont know how to do it... Help plz.

Answers (1)

Geoff Hayes
Geoff Hayes on 17 Jun 2014
You mention that line eight should be skipped - is that because there is only one number in that line? Are valid lines only those with 3 numbers?
Once you have opened your file and ensured that the file descriptor is valid, use a while loop to iterate over each line in the file (with the condition ~feof(fid) (type help feof for details on this function). Then, for each line do something like
% get the line
line = fgetl(fid);
% read the three floats into data and get the count of the number
% of floats read
[data,count] = sscanf(line,'%f%f%f');
if count~=3
fprintf('invalid line: %s\n',line);
else
% do something with data
end
Try out the above and see what happens!

Categories

Find more on Migrate GUIDE Apps 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!