what's the difference between | and || in matlab??

 채택된 답변

matt dash
matt dash 2014년 12월 10일
이동: Stephen23 2024년 3월 19일

1 개 추천

Clarification: for short circuit "and" no tests are evaluated after the first "false". For short circuit "or" no tests are evaluated after the first true.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2014년 12월 10일
편집: Sean de Wolski 2014년 12월 10일

2 개 추천

| applies to each element in the array, || applies to a scalar condition:
[1 0 1] | [ 0 0 1]
v.
[1 0 1] || [ 0 0 1]

댓글 수: 4

It is unclear to me what those code examples are supposed to clarify:
[1 0 1] | [0 0 1]
ans = 1×3 logical array
1 0 1
[1 0 1] || [0 0 1]
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.
The | operator does an element-by-element comparison on its inputs and produces an output the same size as the input (as in the first example).
The || operator can only operate on scalars and produces a logical scalar as an output.
The second statement fails because the inputs (operands) are vectors.
DGM
DGM 2024년 12월 2일
편집: DGM 2024년 12월 2일
I hate to nitpick, but I'm bored and have a minor tweak to add:
The || is a scalar operator, and the | operator is elementwise; that's true. The problem is describing what's expected of an elementwise operator's output size (at least if we're going to explicitly describe it in the context of an ancient question).
Now if we're living in 2014, then the statement that the output is the same size as the input would be true. In the present day, the size of the output of an elementwise operator isn't necessarily the same size as the input. That's only the case when the two inputs are the same size.
Assuming that the inputs have compatible size, the output size is the maximum of input sizes (assuming we're using R2016b or newer (or are using bsxfun() in older versions)).
[1 0 1] | [0 0 1] % output is 1x3
ans = 1x3 logical array
1 0 1
[1 0 1] | [0 0 1].' % output is 3x3
ans = 3x3 logical array
1 0 1 1 0 1 1 1 1
Even without this addendum, I think that @Steve Van Hooser's comment is a more meaningful answer than the original. The short-circuit functionality is really secondary to the fact that || is scalar.
Nice addition. I don't see how to give a thumbs up so I will do it in words.

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

카테고리

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

제품

태그

질문:

2014년 12월 10일

댓글:

2024년 12월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by