While loop ends unexpectedly
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Bob Thompson
am 30 Apr. 2018
Kommentiert: Walter Roberson
am 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 Kommentare
Akzeptierte Antwort
Ameer Hamza
am 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 Kommentare
Ameer Hamza
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!