How to code "if (a and b) or (c and d)"

10 ビュー (過去 30 日間)
CA
CA 2016 年 12 月 5 日
コメント済み: CA 2016 年 12 月 5 日
I'm writing a code where I need a conditional statement something like the following:
x = 1;
y = 2;
if (((x || y == 1) && (x || y == 3))) || (((x || y == 2) && (x || y == 3))
fprintf('true');
else
fprintf('false');
end;
I tried this, but it keeps outputting "true", when I want it to output "false". I want it to say "If (x or y is 1) and (x or y is 3), or if (x or y is 2) and (x or y is 3), then...". But that clearly isn't what this is saying. Please help!

採用された回答

Stephen23
Stephen23 2016 年 12 月 5 日
編集済み: Stephen23 2016 年 12 月 5 日
This does not do what you want (because you are not comparing x with anything, so MATLAB treats the x as true if it is non-zero):
if (((x || y == 1) && ...
You have to compare x first, then perform the or operation:
if (((x==1 || y==1) && ...
You can try this yourself:
>> (3 || 2==4) % 3 is non-zero, treated as true, therefore output is true
ans = 1
>> (3==4 || 2==4) % test if 3==4 and 2==4
ans = 0
  1 件のコメント
CA
CA 2016 年 12 月 5 日
Yeah, I realized this about 10 minutes after I posted the question, but didn't know how to find my question again to correct my mistake. Thanks though!

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

その他の回答 (0 件)

カテゴリ

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