What's the difference between & and && in MATLAB? - matlab

What is the difference between the & and && logical operators in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)
A & B (A and B are evaluated)
A && B (B is only evaluated if A is true)

&& and || take scalar inputs and short-circuit always. | and & take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.
See these doc pages for more information.

As already mentioned by others, & is a logical AND operator and && is a short-circuit AND operator. They differ in how the operands are evaluated as well as whether or not they operate on arrays or scalars:
& (AND operator) and | (OR operator) can operate on arrays in an element-wise fashion.
&& and || are short-circuit versions for which the second operand is evaluated only when the result is not fully determined by the first operand. These can only operate on scalars, not arrays.

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:
They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.
See more here.

& is a logical elementwise operator, while && is a logical short-circuiting operator (which can only operate on scalars).
For example (pardon my syntax).
If..
A = [True True False True]
B = False
A & B = [False False False False]
..or..
B = True
A & B = [True True False True]
For &&, the right operand is only calculated if the left operand is true, and the result is a single boolean value.
x = (b ~= 0) && (a/b > 18.5)
Hope that's clear.

&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if or while loop expressions.

A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...
As others have mentioned, the short-circuiting behavior of &&/|| is similar to most C-like languages. That similarity / familiarity is generally considered a point in its favor.
Using the && or || forms forces you to write the full code for deciding your intent for vector arguments. When a = [1 0 0 1] and b = [0 1 0 1], is a&b true or false? I can't remember the rules for MATLAB's &, can you? Most people can't. On the other hand, if you use && or ||, you're FORCED to write the code "in full" to resolve the condition.
Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.

Related

if statement with 'or' operator gives different results when conditions are swapped

I'm using strfind with an 'or' comparison like so:
name='hello';
if strfind(name,'hello') | strfind(name,'hi')
disp('yes!')
end
>> yes!
The if statement must evaluate as true, since yes! is displayed.
In contrast, MATLAB doesn't return yes! if the statements are swapped:
if strfind(name,'hi') | strfind(name,'hello')
disp('yes!')
end
Why?
This is because short-circuiting. Short-circuited logical operators are a thing to speed up code. You can have
if veryShort | superlongComputation
so what MATLAB does is first evaluate veryShort and if it is true, then no need to evaluate the second one! The if condition is already met.
In your case strfind(name,'hello') returns 1, but strfind(name,'hi') returns [].
In the first example, as the first thing evaluated returns 1, you get to the display. However in the second case, it returns [], therefore MATLAB evaluates the second thing in the if, and returns 1. Then MATLAB applies the or operations where [] | 1 is an 0x0 empty logical array, so the if is not true.
Note, generally you want to use || to enforce short-circuiting, but | also does it, if it is inside a while or an if:
https://uk.mathworks.com/matlabcentral/answers/99518-is-the-logical-operator-in-matlab-a-short-circuit-operator
Both of the following conditions are empty []:
name='hello';
strfind(name,'hello') | strfind(name,'hi'); % = []
strfind(name,'hi') | strfind(name,'hello'); % = []
As referenced in Ander's answer, the | operator is using short circuiting to skip evaluation of the second condition if the first is false (or empty).
Some quick debugging will give you better understanding if we ignore short-circuiting:
strfind(name,'hi'); % = []
strfind(name,'hello'); % = 1
In both cases you are doing "if empty or non-zero", which is empty and "if []" is false (that conditional statement won't be executed).
What you want to use to be explicit is something like this:
if ~isempty(strfind(name, 'hello')) & ~isempty(strfind(name, 'hi'))
disp('yes!')
end
Here, we guarantee that everything being evaluated in the if statement is a Boolean variable, not empty or an index like strfind returns, so unexpected results are less likely.
There are simpler methods, like using strcmp or ismember if your strings should match exactly. Or contains if you have R2016b or newer:
if contains('hello', {'hello','hi'})
disp('yes!');
end

What is the difference between Logical and Comparison operators in MySQL?

Studying MySQL I came to some confusion about operators categorization in MySQL.
NOT is a Logical operator (Details)
while NOT LIKE, LIKE, IS NOT, IS NULL are Comparison operators. (Details)
I'm unable to grasp the real difference.
A logical operator's operands are booleans; whereas comparison operators may have operands of any type.
The comparison operators test the relationship between their operands according to an ordering over the operands' type set, and return a boolean result: 1 < 2, 'hello' > 'aardvark', CURRENT_DATE = '2013-12-30', 'peanut' LIKE 'pea%', 'walnut' NOT LIKE 'pea%', '' IS NOT NULL, etc.
Booleans, on the other hand, don't have an "ordering" by which such relationships can be established*—it's pretty meaningless, for example, to say that FALSE < TRUE. Instead, we think about them in terms of their "truth" and the operators which act upon them in terms of their logical validity: TRUE AND TRUE, FALSE XOR TRUE, NOT FALSE, etc.
Of course, there are many situations where the same logical result can be expressed in multiple ways—for example:
1 < 2 is logically the same as both 2 > 1 and NOT (1 >= 2)
'walnut' NOT LIKE 'pea%' is logically the same as NOT ('walnut' LIKE 'pea%')
'' IS NOT NULL is logically the same as NOT ('' IS NULL)
However, negating a comparison involves a logical operation (negation) in addition to the comparison operation, whereas a single comparison operation that immediately yields the desired result is typically more concise/readable and may be easier for the computer to optimise.
* Some languages (such as MySQL) don't have real boolean types, instead using zero and non-zero integers to represent FALSE and TRUE respectfully. Consequently an ordering does exist over their booleans, albeit that doesn't affect the conceptual distinction.
Simply put, NOT LIKE, LIKE, IS NOT are used to compare two values. For example :
SELECT * FROM `table_name` WHERE `name` NOT LIKE `examplename`;
SELECT * FROM `table_name` WHERE `key_col` IS NULL;
NOT returns the inverse of the value. It's same as !=, for the most part. Example :
SELECT * FROM `student` WHERE NOT (student_id = 1);
The operator returns 1 if the operand is 0 and returns 0 if the operand is nonzero. It returns NULL if the operand is NOT NULL.
Visit : MySQL Operators
Visit : NOT ! Operator
In simple words:
Comparison operator compares 2 values in different manners as per operator used like ==, !=, >, <, >=, <= and others.
On the other hand, Logical operator will check conditions (more than 1) returns by comparison operator and then performs the operation as per result.

What's the difference between | and || in 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.
For example, consider
x = a && 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.
Now consider this expression:
NeedToMakeExpensiveFunctionCall && 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.
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
then the call to ExpensiveFunctionCall would never be skipped.
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)
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.
For a longer discussion of short-circuit evaluation, refer to the Wikipedia article on the subject.
Logical Operators
MATLAB offers three types of logical operators and functions:
| is Element-wise — operate on corresponding elements of logical arrays.
Example:
vector inputs A and B
A = [0 1 1 0 1];
B = [1 1 0 0 1];
A | B = 11101
|| is Short-circuit — operate on scalar, logical expressions
Example:
|| : Returns logical 1 (true) if either input, or both, evaluate to true, and logical 0 (false) if they do not.
Operand: logical expressions containing scalar values.
A || B (B is only evaluated if A is false)
A = 1;
B = 0;
C =(A || (B = 1));
B is 0 after this expression and C is 1.
Other is, Bit-wise — operate on corresponding bits of integer values or arrays.
reference link
|| is used for scalar inputs
| takes array input in if/while statements
From the source:-
Always use the && and || operators when short-circuiting is required.
Using the elementwise operators (& and |) for short-circuiting can
yield unexpected results.
Short-circuit || means, that parameters will be evaluated only if necessarily in expression.
In our example expr1 || expr2 if expr1 evaluates to TRUE, than there is no need to evaluate second operand - the result will be always TRUE. If you have a long chain of Short-circuit operators A || B || C || D and your first evaluates to true, then others won't be evaluated.
If you substitute Element-wise logical | to A | B | C | D then all elements will be evaluated regardless of previous operands.
| represents OR as a logical operator. || is also a logical operator called a short-circuit OR
The most important advantage of short-circuit operators is that you can use them to evaluate an expression only when certain conditions are satisfied. For example, you want to execute a function only if the function file resides on the current MATLAB path. Short-circuiting keeps the following code from generating an error when the file, myfun.m, cannot be found:
comp = (exist('myfun.m') == 2) && (myfun(x) >= y)
Similarly, this statement avoids attempting to divide by zero:
x = (b ~= 0) && (a/b > 18.5)
You can also use the && and || operators in if and while statements to take advantage of their short-circuiting behavior:
if (nargin >= 3) && (ischar(varargin{3}))

MATLAB logical operators: && vs &

If I want to ensure that an if statement only executes if BOTH of two conditions are true, should I be using & or && between the clauses of the statement?
For example, should I use
if a == 5 & b == 4
or
if a == 5 && b == 4
I understand that the former is elementwise and the latter is capable of short-circuiting but am not clear on what this means.
For a scalar boolean condition I'd recommend you use &&. Short-circuiting means the second condition isn't evaluated if the first is false, but then you know the result is false anyway. Either & or && one will be true only if both sides of the expression are true, but & can return a matrix result if one of the operands is a matrix.
Also, I believe in Matlab comparisons should be done with ==, not with = (assignment).

Unable to add a condition to a while loop in Matlab

I have a while loop which looks like this:
while ((min_t_border>0) && (colided_border_num > 0) && (~(min_t>0)))
...
end
I want to add to it another condition: (exit_border_point ~= false) or (exit_border_point)
when I put ether of the conditions above in an if statement it works. But when I try to add it as an additional condition to the while, or even when I try to add another condition to the if, for example I've tried if ((exit_border_point ~= false) && (true)) it tells me:
"Operands to the || and && operators must be convertible to logical scalar values."
What am I doing wrong?
*exit_border_point gets ether a (3x1) vector or false
Since exit_border_point can be a vector, try using the any or all functions, like this:
if (~any(exit_border_point))
As you can probably guess, any returns true if anything in the array evaluates to true and all returns true if everything in the array is true. They're kind of like vector equivalents to || and &&.
For the condition to make sense in the context of an if or while statement, it should evaluate to a scalar.
Thus, you should write
all(exit_border_point)
(which is equivalent to all(exit_border_point == true)), if you want true if all are true. Replace all with any if you want to exit the while-loop as soon as any exit_border_point is true.
Note that && and || only work for scalars. They're short-cut operators in that the second statement won't be evaluated if the first one determines the outcome (e.g. evaluates to false in case of &&. If you want to element-wise compare arrays, use & and |.
If exit_border_point is a 3x1 vector then (exit_border_point ~= false) also returns a 3x1 vector, hence the error. Use this condition instead:
~isequal(exit_border_point, false)