What is the difference between the &
and &&
logical operators in MATLAB?
相关问题
- Extract matrix elements using a vector of column i
- How do you get R's null and residual deviance
- How to display an image represented by three matri
- OpenCV - Is there an implementation of marker base
- Require explanation for the output
相关文章
- How do I append metadata to an image in Matlab?
- How can I write-protect the Matlab language?
- `std::sin` is wrong in the last bit
- Escape sequence to display apostrophe in MATLAB
- Vertical line fit using polyfit
- How to do parallel “either-side” short-circuiting
- Reading .mat file using C: how to read cell-struct
- Check for multiple values when using comparison op
&&
and||
take scalar inputs and short-circuit always.|
and&
take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.See these doc pages for more information.
Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:
See more here.
The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)
A & B (A and B are evaluated)
A && B (B is only evaluated if A is true)
A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...
Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.
&& and || are short circuit operators operating on scalars. & and | always evaluate both operands and operate on arrays.
As already mentioned by others,
&
is a logical AND operator and&&
is a short-circuit AND operator. They differ in how the operands are evaluated as well as whether or not they operate on arrays or scalars:&
(AND operator) and|
(OR operator) can operate on arrays in an element-wise fashion.&&
and||
are short-circuit versions for which the second operand is evaluated only when the result is not fully determined by the first operand. These can only operate on scalars, not arrays.