필터 지우기
필터 지우기

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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by