如果带有'或'运算符的语句在交换条件时给出不同的结果

Mic*_*aël 4 matlab string-comparison logical-operators

我正在使用strfind'或'比较,如下所示:

name='hello';
if strfind(name,'hello') | strfind(name,'hi')
    disp('yes!')
end

>> yes!
Run Code Online (Sandbox Code Playgroud)

if语句必须为评估true以来,yes!被显示出来.

相反,yes!如果交换语句,MATLAB不会返回:

if strfind(name,'hi') | strfind(name,'hello')
    disp('yes!')
end
Run Code Online (Sandbox Code Playgroud)

为什么?

And*_*uri 5

这是因为短路.短路的逻辑运算符是加速代码的一种方法.你可以有

if veryShort | superlongComputation
Run Code Online (Sandbox Code Playgroud)

所以MATLAB首先要做的是评估veryShort,如果是真的,那么就不需要评估第二个了!if条件已经满足.

在你的情况下strfind(name,'hello')返回1,但strfind(name,'hi')返回[].

在第一个示例中,当第一个评估返回时1,您将进入显示.但是在第二种情况下,它返回[],因此MATLAB评估第二种情况if,并返回1.然后MATLAB将or操作应用于[] | 1a 0x0 empty logical array,所以if不是这样.

注意,一般你想用来||强制短路,但|如果它在一个while或一个内if:

https://uk.mathworks.com/matlabcentral/answers/99518-is-the-logical-operator-in-matlab-a-short-circuit-operator