While loop ends unexpectedly

5 visualizaciones (últimos 30 días)
Bob Thompson
Bob Thompson el 30 de Abr. de 2018
Comentada: Walter Roberson el 30 de Abr. de 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?

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 30 de Abr. de 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 comentarios
Ameer Hamza
Ameer Hamza el 30 de Abr. de 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.
Walter Roberson
Walter Roberson el 30 de Abr. de 2018
If you want to check for end of file, use isnumeric()

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by