Hello,
when can I use and | in command if?
For example:
if a||b
if a| b
Thank you

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 26일

1 개 추천

a||b will return 1 if the first expression a is true, without evaluating the second expression b
Example
2==2 || hhh % even hhh is not defined Matlab will not evaluate it, because the first expression 2==2 is true
a&&b will return 0 if the first expression a is false without evaluating the second expression b

댓글 수: 6

john
john 2014년 4월 26일
OK Azzi,
what about a|b? What is different?
Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 26일
편집: Azzi Abdelmalek 2014년 4월 26일
a | b and a||b should give the same result, the difference is: Matlab when evaluating a|b, a and b are both evaluated, try
2==2 | h
In this case the first expression is 2==2, which is true, we know that if one of the two expression is true, then the result is true, without evaluating the second expression, but by using | Matlab will evaluate the second expression which is h, in our case h is not defined, that's why you will get an error.
john
john 2014년 4월 26일
ok, thank you
john
john 2014년 4월 26일
but result :
if 2==2 || h
fff=1
end
is the same like:
if 2==2 | h
fff=1
end
but for this I get error:
if h | 2==2
fff=1
end
Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 26일
편집: Azzi Abdelmalek 2014년 4월 26일
Because Matlab, in both case (| or | | ) evaluate the first expression h which is not defined.
Azzi Abdelmalek
Azzi Abdelmalek 2014년 4월 26일
It's better to use | |, this can make your code faster, when the first expression is true, Matlab doesn't need to evaluate the second one.

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

추가 답변 (1개)

dpb
dpb 2014년 4월 26일

1 개 추천

Depends entirely on the purpose...the double logical operators short-circuit and return only a scalar whereas the single ones are point-by-point operators over the full dimension of the two operands and return a matrix of the same size.
doc relop
has further details and info

댓글 수: 2

john
john 2014년 4월 26일
a=3;
b=2;
What is better ?
if a==3 || b==2
end;
Or
if a==3 | b==2
end;
Jan
Jan 2014년 4월 27일
편집: Jan 2014년 4월 27일
@John: When a and b are scalars, both versions are equivalent. But the first one || is slightly faster (nano-seconds for scalar operands...), when the first expression is true already. When a and/or b is a vector, you need the , which is equivalent to |or(a==3, b==2). But then the vector expression in the if command is tricky, because implicitly this is performed:
expr = or(a==3, b==2);
if all(expr) && ~isempty(expr) ...
This is at least confusing or can even be a bug, if this behavior is not intended.

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

카테고리

도움말 센터File Exchange에서 Data Types에 대해 자세히 알아보기

태그

질문:

2014년 4월 26일

편집:

Jan
2014년 4월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by