Error when using isempty in a while loop
7 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (2 件)
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
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
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
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!