Using logical operators within if statement

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 日

1 投票

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 日

1 投票

I think you need to use or (||) .. instead of &
Andrei Bobrov
Andrei Bobrov 2013 年 12 月 29 日

1 投票

while true
um=input('um(Between 0 and 1) =');
if um<0 || um>1
disp('Enter a valid value');
else
break;
end
end

カテゴリ

ヘルプ センター および File ExchangeMATLAB Mobile Fundamentals についてさらに検索

質問済み:

2013 年 12 月 29 日

コメント済み:

2013 年 12 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by