zhouyang664 发表于 2010-10-27 12:30

关于逻辑操作符|,&与||,&&的区别

    在进行逻辑操作时,符号|,&在遇到空矩阵时均返回[],如下:
>> 4|[]%只要操作数有[],就返回[]
ans =
   []
>> 4&[]
ans =
   []
>> 1|[]
ans =
   []
>> 0&[]
ans =
   []
   而符号||,&&则在第一个条件满足时就返回判断结果,不再判断第二个条件,如下:
>> 4||[]%4为真,直接返回1
ans =
   1
>> 0&&[] %0为假,直接返回0
ans =
   0
   但||,&&似乎不支持[]作为有效操作数,如下:
>> 0||[] % 根据0,不能判断操作结果,执行第二个操作数,出错:
??? Operands to the || and && operators must be convertible to logical scalar
values.
>> 1&&[] % 根据1,不能判断操作结果,执行第二个操作数,出错:
??? Operands to the || and && operators must be convertible to logical scalar
values.

    但在if语句中 |,&和||,&&的行为就相同了:
if 4 | []
    disp('Must be true')
end
Must be true
if 4 || []
    disp('Must be true')
end
Must be true
   官方文件称||,&&的这种行为为short-circuit,常用于if和while语句中!

欢迎大家一起探讨!

qibbxxt 发表于 2010-10-27 14:25

按照help中的解释,区别是Note the difference between the elementwise and short-circuit logical operators. Short-circuit operators, such as && and ||, test only as much of the input expression as necessary. In the second part of this example, it makes no difference that B is undefined because the state of A alone determines that the expression is false:

A = 0;
A & B
??? Undefined function or variable 'B'.

A && B
ans =
   0当然,还有
&   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.当然在实际运用过程中,需要达到自己的效果是,如果用&不行,就用&&,反正也不多,试一试呗

zhouyang664 发表于 2010-10-27 16:31

好,学习学习!

ChaChing 发表于 2010-10-28 00:01

0||[]及1&&[], 不支持[]作为有效操作数
新学到, 谢谢分享!
页: [1]
查看完整版本: 关于逻辑操作符|,&与||,&&的区别