MATLAB: While loop ends unexpectedly

asciifgetlifMATLABwhile

I have an executable file which creates an ascii file containing numbers and characters mixed. I have written a while and if loop combo to read and check each line for data that I want.
while line~=-1;
line = fgetl(file); % Read next line

count = count + 1; % Line count

if length(line)<5; % Skip blank and short lines

elseif strcmp(line(3:25),'Desired Trigger 1')==1; % Check for first trigger
% Gather data
elseif ...
...
end % If check
end % While
This combo reads the data perfectly fine, except when it reaches a blank line where line = ''. This line clears through the if statement properly as a blank line, but for some reason the while loop considers it to be a break condition and exits the while loop. If I make the following adjustment the script runs fine, but I prefer not to have infinite loops in my scripts.
while 1 == 1;
line = fgetl(file); % Read next line
count = count + 1; % Line count
if line == -1; % End of file condition
break
elseif length(line)<5; % Skip blank and short lines
...
Does anybody know why the first version breaks the loop but the second does not?

Best Answer

Because in the first case, the fgetl() function returns an empty vector char vector, and comparison of an empty vector with -1 produce an empty logical vector which MATLAB interpret as false. To avoid this in the first case before the end of while loop add
if isempty(line)
line = ' '; % add a dummy character
end
this will prevent the while condition to fail.