2016-09-14 84 views
1

我的印象是||是MATLAB中的“或”语句。也许有人可以解释我所看到的令人困惑的行为:有条件的“或”语句在MATLAB中

a = 2; 

a == 2  %returns ans = 1 (true) 

a == 2 || 3 %returns ans = 1 (true) 

a == 3 || 4 %returns ans = 1 (true)??!! 

我在这里错过了什么? 'a'既不是3也不是4,所以不应该是

a == 3 || 4 

return ans = 0(false)?

回答

6

表达

a == 3 || 4 

则评价道:

a == 3  => false 
then 
false || 4 => true 
如果你想检查是否等于3或4

你应该写

(a == 3) || (a == 4) 

这是这样评价

a == 3   => false 
then 
a == 4   => false 
then 
false || false => false 
0

托马斯的回答是对这里发生了什么的一个很好的解释;另一种可以将变量与多个答案进行比较的方法是使用any()函数。

solutions = [3 4]; 
any(a==solutions); 

a==solutions行创建的矩阵相同大小的解决方案,其中包含在其中indecies其中所述条件为真1的和0的地方它是假的。

几个例子:

any(isprime([17:24])); %returns true; 17, 19 and 23 are prime 
any(isinteger(sqrt([17:24]))); %(test for square number) returns false; no square numbers in this range 
any(mod(magic(3)(:),6)==3); %returns true; 9 mod 6 == 3. Note (:) inserted so that any is evaluated against all entries of the square matrix created by magic 
0

a == 3 || 4 %returns ans = 1 (true) ?? !!

上述行为的原因是由于MATLAB中除'0'以外的任何实数始终评估为true。

所以这里发生了什么是

  • 表达a == 3首先是评估,发现false
  • 接下来,评估表达false || 4
  • 由于'4'是一个非零的实数,因此得到的表达式为false || true,其计算结果为true

为了得到想要的结果,使用(a == 3) || (a == 4),其评价为false || false,其返回false