フィルターのクリア

Error when using isempty in a while loop

7 ビュー (過去 30 日間)
Taniel Goetcherian
Taniel Goetcherian 2017 年 10 月 6 日
編集済み: Cedric 2017 年 10 月 6 日
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.

回答 (2 件)

Cedric
Cedric 2017 年 10 月 6 日
編集済み: Cedric 2017 年 10 月 6 日
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 件のコメント
Cedric
Cedric 2017 年 10 月 6 日
編集済み: Cedric 2017 年 10 月 6 日
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
OCDER 2017 年 10 月 6 日
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 件のコメント
Taniel Goetcherian
Taniel Goetcherian 2017 年 10 月 6 日
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?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by