问题描述
MATLAB中的|
和||
逻辑运算符有什么区别?
What is the difference between the |
and ||
logical operators in MATLAB?
推荐答案
I'm sure you've read the documentation for the short-circuiting operators, and for the element-wise operators.
一个重要的区别是,逐元素运算符可以对数组进行运算,而短路运算符仅适用于标量逻辑操作数.
One important difference is that element-wise operators can operate on arrays whereas the short-circuiting operators apply only to scalar logical operands.
但是可能的关键区别在于短路问题.对于短路算子,从左到右对表达式进行求值,一旦确定最终结果,就不对其余项求值.
But probably the key difference is the issue of short-circuiting. For the short-circuiting operators, the expression is evaluated from left to right and as soon as the final result can be determined for sure, then remaining terms are not evaluated.
例如,考虑
x = a && b
如果a
评估为false
,则我们知道a && b
评估为false
,而与b
评估的内容无关.因此,无需评估b
.
If a
evaluates to false
, then we know that a && b
evaluates to false
irrespective of what b
evaluates to. So there is no need to evaluate b
.
现在考虑以下表达式:
NeedToMakeExpensiveFunctionCall && ExpensiveFunctionCall
我们认为ExpensiveFunctionCall
需要很长时间才能评估.如果我们可以执行其他一些便宜的测试,从而允许我们跳过对ExpensiveFunctionCall
的调用,则可以避免调用ExpensiveFunctionCall.
where we imagine that ExpensiveFunctionCall
takes a long time to evaluate. If we can perform some other, cheap, test that allows us to skip the call to ExpensiveFunctionCall
, then we can avoid calling ExpensiveFunctionCall.
因此,假设NeedToMakeExpensiveFunctionCall
计算为false
.在这种情况下,因为我们使用了短路运算符,所以不会调用ExpensiveFunctionCall
.
So, suppose that NeedToMakeExpensiveFunctionCall
evaluates to false
. In that case, because we have used short-circuiting operators, ExpensiveFunctionCall
will not be called.
相反,如果我们使用逐元素运算符并编写如下函数:
In contrast, if we used the element-wise operator and wrote the function like this:
NeedToMakeExpensiveFunctionCall & ExpensiveFunctionCall
然后将永远不会跳过对ExpensiveFunctionCall
的调用.
then the call to ExpensiveFunctionCall
would never be skipped.
事实上,我确实希望 MATLAB文档您已经阅读过,其中包括一个很好的例子,很好地说明了这一点:
In fact the MATLAB documentation, which I do hope you have read, includes an excellent example that illustrates the point very well:
x = (b ~= 0) && (a/b > 18.5)
在这种情况下,如果b
为零,则无法执行a/b
.因此,对b ~= 0
的测试.使用短路运算符意味着,当b
为零时,我们避免计算a/b
,因此避免了会出现的运行时错误.显然,基于元素的逻辑运算符将无法避免运行时错误.
In this case we cannot perform a/b
if b
is zero. Hence the test for b ~= 0
. The use of the short-circuiting operator means that we avoid calculating a/b
when b
is zero and so avoid the run-time error that would arise. Clearly the element-wise logical operator would not be able to avoid the run-time error.
有关短路评估的详细讨论,请参见上的 Wikipedia文章主题.
For a longer discussion of short-circuit evaluation, refer to the Wikipedia article on the subject.
这篇关于和|有什么区别?和||在MATLAB中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!