필터 지우기
필터 지우기

How to use two logical operation inside a if condition?

조회 수: 15 (최근 30일)
Asim Ismail
Asim Ismail 2017년 8월 19일
댓글: Asim Ismail 2017년 8월 19일
I have three statements in a if condition and they are executed when the logical operations are true. For example I have two variables a and b, and their values are:
a=7;
b=5;
if a=7 && b=a || b<a
do something
end
Can someone please tell me what is the correct way to perform second operation (b=a | | b<a) first, and then do && operation between the result and the first statement (a=7)?

채택된 답변

Star Strider
Star Strider 2017년 8월 19일
편집: Star Strider 2017년 8월 19일
They are evaluated left-to right. See the documentation on Logical Operators: Short-Circuit && || (link) for a full discussion.
When in doubt, experiment to understand how the logic works:
a=7;
b=5;
L1 = a==7 && b==a || b<a
a=5;
b=5;
L2 = (b==a || b<a) && a==7
a=6;
b=5;
L3 = (b==a || b<a) && a==7
... and others as you want to study them.
Also, you need to use ‘double equals’ here:
if a==7 && b==a || b<a
  댓글 수: 3
Asim Ismail
Asim Ismail 2017년 8월 19일
Thank you Star Strider, got it
Star Strider
Star Strider 2017년 8월 19일
My pleasure.

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

추가 답변 (1개)

Image Analyst
Image Analyst 2017년 8월 19일
Like this:
a=7;
b=5;
if a==7 && (b==a || b<a)
% do something
end
Make sure you use double equals for comparison, rather than single equals which does assignment.
Since a has to equal 7, the if won't be true unless b is equal to or less than 7. So you could do this
if a == 7 && b <= 7
which is the same thing.

카테고리

Help CenterFile Exchange에서 Graphics Object Properties에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by