Skip to main content
Logo image

Section 7.2 Built-In Logical Operator Functions

MATLAB has built-in functions that carry out logical operations.
Table 7.3. Built-In Logical Operator Functions
Function Operation
and(a,b) equivalent to a & b
or(a,b) equivalent to a | b
not(a) equivalent to ~a
xor(a,b) Exclusive OR (XOR)
all(a) 1 if all elements of a are true, else 0
any(a) 1 if any elements of a are true, else 0
find(a) returns indices of nonzero elements
find(a>d) returns indices of elements that are larger than d
Let’s take a look at some examples:
>> vec = [2 3 4 -2 3 4]
vec =
    2  3  4  -2  3  4
The following command finds the indices of all elements that are positive:
>> pos_elem = find(vec > 0)
pos_elem =
    1  2  3  5  6
Now that we have these indices we can use them to address the actual elements in the original vector:
>> vec(pos_elem)
ans =
    2  3  4  3  4
You can use multiple operators in one expressions and once you do so you need to know which of these operators will get executed ahead of which others. This is called operator precedence. In the following table, precedence goes from top to bottom, meaning that operators above others in the table have higher precedence.
Table 7.4. Operator Precedence
Operator Operation
() parentheses
^ exponentiation
~ logical NOT
* / multiplication and division
+ - addition and subtraction
> < >= <= == ~= relational and equality operators
& && logical AND
| || logical OR
= assignment