While reading data from text file line by line using fget1, If error on data how to go to next line?
15 views (last 30 days)
Show older comments
Hi, I am new to this form so sorry for any mistakes.
My question is what I am after. So I have set of data been read line by line using fget1, but my data can have sometimes lines or some data missing.
So what I need program to do is if there is empty line but not EOf, or if data missing within each line just fill with NaN or skip and go to next line.
example of my code:
try
tline = fgetl(fileID);
while (tline ~= -1)
if (strncmp(tline,'01',2))
%get data
Time_num=addtodate(Time_num,100,'millisecond');
Data = textscan(tline,'%*s%*s%*s%d16%d16%d16%d16%d16%d16%c%c%c%c%c%c\n'...
,'delimiter',',');
DATA(dataLine,:) = cell2mat(Data(1,1:6));
%V_A(dataLine,:)=Data(1,7:12);
Time_Axis(dataLine,:)=Time_num;
dataLine=dataLine+1;
end
end
catch err
errordlg('There has been an error with your Import File.',' File Error #2017');
end
3 Comments
Friedrich
on 29 Aug 2013
The code you posted reads only one line from a file and can result in an endless loop. I guess you miss an additional fgetl inside the while loop. And what kind of error do you get?
Accepted Answer
Ken Atwell
on 30 Aug 2013
It would be up to your line processing code to not generate an error on an malformed line. I would write code something like this:
while ~feof(fileID)
tLine = fgetl(fileID);
% Process line here (and don't generate an erro)
end
The feof/fgetl function are called each loop iteration, regardless of the success or failure of the previous line's processing.
2 Comments
Walter Roberson
on 30 Aug 2013
Remember to test ischar(tLine) before using it, as feof() only tells you whether a read operation already encountered end-of-file, not that a read operation would encounter end-of-file.
More Answers (0)
See Also
Categories
Find more on Data Import from MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!