声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 2649|回复: 3

[编程技巧] 关于逻辑操作符|,&与||,&&的区别

[复制链接]
发表于 2010-10-27 12:30 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
    在进行逻辑操作时,符号|,&在遇到空矩阵时均返回[],如下:
>> 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语句中!

欢迎大家一起探讨!

评分

1

查看全部评分

回复
分享到:

使用道具 举报

发表于 2010-10-27 14:25 | 显示全部楼层
按照help中的解释,区别是
  1. 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:

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

  5. A && B
  6. ans =
  7.      0
复制代码
当然,还有

  1. &   Element-wise Logical AND.
  2.       A & B is a matrix whose elements are logical 1 (TRUE) where both A
  3.       and B have non-zero elements, and logical 0 (FALSE) where either has
  4.       a zero element. A and B must have the same dimensions (or one can
  5.       be a scalar).
  6. && Short-Circuit Logical AND.
  7.       A && B is a scalar value that is the logical AND of scalar A and B.
  8.       This is a "short-circuit" operation in that MATLAB evaluates B only
  9.       if the result is not fully determined by A. For example, if A equals
  10.       0, then the entire expression evaluates to logical 0 (FALSE), regard-
  11.       less of the value of B. Under these circumstances, there is no need
  12.       to evaluate B because the result is already known.
复制代码
当然在实际运用过程中,需要达到自己的效果是,如果用&不行,就用&&,反正也不多,试一试呗
 楼主| 发表于 2010-10-27 16:31 | 显示全部楼层
好,学习学习!
发表于 2010-10-28 00:01 | 显示全部楼层
0||[]及1&&[], 不支持[]作为有效操作数
新学到, 谢谢分享!
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-5-5 03:50 , Processed in 0.051827 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表