What are the differences between & and && in matlab?

Possible duplicate:
What is the difference between &&& in MATLAB?

This is from the help.

& Element-wise Logical AND. A & B is a matrix whose elements are logical 1 (TRUE) where both A and B have non-zero elements, and logical 0 (FALSE) where either has a zero element. A and B must have the same dimensions (or one can be a scalar). && Short-Circuit Logical AND. A && B is a scalar value that is the logical AND of scalar A and B. This is a "short-circuit" operation in that MATLAB evaluates B only if the result is not fully determined by A. For example, if A equals 0, then the entire expression evaluates to logical 0 (FALSE), regard- less of the value of B. Under these circumstances, there is no need to evaluate B because the result is already known. 

I wonder if && perform the same function? Regardless of size A and B, if they are the same size?

Is && more effective than &, why should we use && all the time?

A script is testing while fulfilling two conditions in while .

+4
source share
3 answers

Short answer

  • When A and B are scalars , use &&
  • When A and B are vectors , use &

Long answer

-When you use A && B , it evaluates A , if A is zero, then it does not evaluate B , because no matter what B , the answer is 0.

-However, when A and B are vectors: firstly, using && causes an error . Secondly, & will use some fast CPU instruction set to compute multiple operations at the same time. Third, in this situation, Matlab cannot use the previous lazy estimate & , because it does not know how to evaluate only a subset of B

+5
source

The difference is B.

As explained in your reference text, && does not evaluate B if A is false. This is not necessary, because the whole result of A and B is false, so why waste effort.

On the other hand, sometimes you need to evaluate both A and B (think about the side effects, evaluating B can do more than just return the value), therefore & will evaluate both A and B each time.

+4
source

Given the expression A & B compared to A && B difference is that the AND short circuit logic never evaluates B if A is easily false. This can be useful if, for example, rating B is time consuming.

For instance:

 if( shortcalculation(A) && longcalculation(B) ) ... 

If shortcalculation(A) already returns false, we can reserve longcalculation(B) using the AND short circuit logic.

If you want A and B to always be evaluated regardless of their truth value, use & instead instead.

+2
source

Source: https://habr.com/ru/post/1383494/


All Articles