Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sometimes I use | and sometimes || for "or" in MATLAB?

Tags:

matlab

I want to check if x is NaN or inf. If it is, i replace it with 1.

if isnan(x) || isinf(x)
    x = 1;
end

vs

x(isnan(x)|isinf(x)) = 1;

Are they both correct in expressing "or"? It seems that they both work but I am unsure and I don't know why sometimes I use | and sometimes || for "or" in MATLAB?

like image 900
Ka-Wa Yip Avatar asked Nov 27 '25 00:11

Ka-Wa Yip


1 Answers

They are not quite the same. The right hand argument of || is not evaluated if the result of the left hand side is sufficient to yield the answer. This is called short-circuitting and also applies to &&.

For |, both arguments are always evaluated.

Furthermore, || returns a straightforward 1 or 0 (true or false).

But | computes a bitwise OR, so the result is subtly different. For the corresponding & operator this can even be pernicious: For example if the left hand side returns binary 0b01 and the right hand side binary 0b10 then, although both arguments are non-zero, the result of the expression is zero.

In your case, use if isnan(x) || isinf(x)

like image 86
Bathsheba Avatar answered Nov 29 '25 16:11

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!