Error when using isempty in a while loop

16 views (last 30 days)
Taniel Goetcherian
Taniel Goetcherian on 6 Oct 2017
Edited: Cedric on 6 Oct 2017
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.

Answers (2)

Cedric
Cedric on 6 Oct 2017
Edited: Cedric on 6 Oct 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 Comment
Cedric
Cedric on 6 Oct 2017
Edited: Cedric on 6 Oct 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

Sign in to comment.


OCDER
OCDER on 6 Oct 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
  1 Comment
Taniel Goetcherian
Taniel Goetcherian on 6 Oct 2017
Thing is I'm trying to input a number, not a string. Any advice on how to make it not error out when doing so?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!