While loop ends unexpectedly
5 views (last 30 days)
Show older comments
Bob Thompson
on 30 Apr 2018
Commented: Walter Roberson
on 30 Apr 2018
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?
0 Comments
Accepted Answer
Ameer Hamza
on 30 Apr 2018
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.
3 Comments
Ameer Hamza
on 30 Apr 2018
Actually, it will be evaluated as a 0 by 0 logical variable. Since a 0 by 0 array does not contain any element and the while loop documentation tells that
"while loop to repeat when condition is true"
so it will break the loop on seeing empty comparison matrix in the condition.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!