Error when using isempty in a while loop
26 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi, I'm trying to make a while loop using two conditions separated by an OR. The loop should continue for as long as 'a' is zero or the user hits enter before typing anything.
Edit: the input is supposed to be a number, not a string.
a=input('Please enter "a" :');
while (a==0 || isempty(a))
a=input('\nCan''t do that m8, try again :');
end
>>Operands to the || and && operators must be convertible to logical scalar values.
I also tried using isempty(a)==1, but that didn't work either.
Any help would be greatly appreciated.
0 comentarios
Respuestas (2)
Cedric
el 6 de Oct. de 2017
Editada: Cedric
el 6 de Oct. de 2017
This thread should answer you question about what your variable a is and how that works:
Just a few extra hints:
>> 123 == 0
ans =
logical
0
>> 'hello' == 0
ans =
1×5 logical array
0 0 0 0 0
>> [] == 0
ans =
0×0 empty logical array
as you can see, the test a==0 can produce outputs of various sizes.
1 comentario
Cedric
el 6 de Oct. de 2017
Editada: Cedric
el 6 de Oct. de 2017
To answer your comment below,
in = NaN ;
while isnan( in ) || in == 0
in = str2double( input( 'Enter a scalar different from 0 : ', 's' )) ;
end
and you can add as many conditional statements as necessary in the loop that test the value of in, set it to NaN if not valid, and print error messages.
in = NaN ;
while isnan( in )
in = str2double( input( 'Enter a scalar different from 0 : ', 's' )) ;
if in <= 0
fprintf( 'Blah!\n' ) ;
in = NaN ;
end
end
OCDER
el 6 de Oct. de 2017
One issue you'll find is that the input will error out for number inputs such as: "1 2 3 4". If you only want string inputs, use input('your message', 's'). Assuming you want to ask for 'a' indefinitely until the user types in 'a', then you could do this instead:
a = input('Please enter "a" : ', 's');
while ~strcmp(a, 'a')
a = input('Can''t do that m8, try again : ', 's');
end
Ver también
Categorías
Más información sobre Logical 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!