Using logical operators within if statement

조회 수: 15 (최근 30일)
Abhivyakti
Abhivyakti 2013년 12월 29일
댓글: Abhivyakti 2013년 12월 30일
This probably is a very silly thing, but somehow I am not getting it right.
I need to input the value of a variable'um' from user. The value should lie within 0<um<1 to be acceptable, else has to be rejected. This is my program :
um=input('um(Between 0 and 1) =');
if um<0 & um>1
um=0;
disp('Enter a valid value');
end
If I try the two conditional statements i.e um<0 and um>1 individually , it works. However, using both the statements together, is accepting values of um greater than 1 as well.
I have tried all possible 'if' statements here, i.e :
if um<0 & um>1
if (um<0) & (um>1)
if (um<0) && (um>1)
if (um<0 && um>1)
Nothing seems to work out. I have done thins in C++ numerous times, but there is some problem with my syntax in MATLAB I guess.
Thanks in advance! :)

채택된 답변

Wayne King
Wayne King 2013년 12월 29일
편집: Wayne King 2013년 12월 29일
You don't want an &, you want an or |
um=input('um(Between 0 and 1) =');
if (um<0 || um>1)
disp('Enter a valid value');
end
How can something be less than 0 and greater than 1? That should be the same in C++.
  댓글 수: 2
Image Analyst
Image Analyst 2013년 12월 29일
Or
uiwait(warndlg('Please enter a value between 0 and 1'));
Abhivyakti
Abhivyakti 2013년 12월 30일
Thankyou soo much :)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Amit
Amit 2013년 12월 29일
편집: Amit 2013년 12월 29일
I think you need to use or (||) .. instead of &

Andrei Bobrov
Andrei Bobrov 2013년 12월 29일
while true
um=input('um(Between 0 and 1) =');
if um<0 || um>1
disp('Enter a valid value');
else
break;
end
end

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by