在matlab中&和&&之间有什么区别?

Tim*_*Tim 3 matlab

可能重复:
MATLAB中&和&&之间有什么区别?

这是来自帮助

  &   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.
Run Code Online (Sandbox Code Playgroud)

我想知道&和&&是否执行相同的功能?无论A和B的尺寸是多少,只要尺寸相同?

是&&更有效,所以我们应该一直使用&&?

一个场景是测试是否同时满足两个条件while.

Oli*_*Oli 5

简答

  • 当A和B是标量时,请使用&&
  • 当A和B是矢量时,请使用&

答案很长

- 当你使用时A && B,它会评估A,如果A为零,那么它就不会评估B,因为无论是什么B,答案都是0.

- 但是,何时AB是向量:首先,使用&&产生错误.其次,&将使用CPU的一些快速指令集同时计算多个和操作.第三,在这种情况下matlab不能使用以前的懒惰评估,&因为它不知道如何只评估一个子集B.