# sheng/logic operators

### From CDS 130

## Contents |

# 1. Objectives

- To introduce the use of logical operators.

# 2. Motivation

- Like relational operators, logical operators are often used to form "conditions" in if statements.
- There are many occasions when we face complex conditions to make a decision. This means that a decision depends upon more than one condition in different ways. Here we combine the conditions with AND or OR.

# 3. Pre-questions

- A boy can be selected in basket ball team only if he is more than 18 years old and has a height of 6 feet.

Q: What are the conditions here?

A: In this statement a boy who wants to be selected in the basket ball team must have both the conditions fulfilled. This means that AND forces both the conditions to be true.

# 4. Slides

## 4.1. Logical Operators

Matlab has three logical operators:

and: A&B and(A,B) or: A|B or(A,B) not: ~A not(A)

The following table shows the results of four different pairs of input values to the logical operators above:

A | B | ~A | ~B | A & B | A | B |
---|---|---|---|---|---|

0 | 0 | 1 | 1 | 0 | 0 |

0 | 1 | 1 | 0 | 0 | 1 |

1 | 0 | 0 | 1 | 0 | 1 |

1 | 1 | 0 | 0 | 1 | 1 |

## 4.2. Precedence of & and | Operators

MATLAB always gives the & operator precedence over the | operator.

Although MATLAB typically evaluates expressions from left to right, the expression a|b&c is evaluated as a|(b&c). It is a good idea to use parentheses to explicitly specify the intended precedence of statements containing combinations of & and |.

## 4.3. Common Errors

The most common errors with logical operators involve the order of operations. In the absence of parenthesis, any NOT operations go first, followed by AND, then finally OR.

## 4.4. Example I

This example shows the logical OR of the elements in the vector u with the corresponding elements in the vector v:

u = [0 0 1 1 0 1]; v = [0 1 1 0 0 1]; u | v ans = 0 1 1 1 0 1

## 4.5. Example II

find those elements of array R that are both greater than 0.3 AND less then 0.9:

R=rand(5,7) R = 0.9501 0.7621 0.6154 0.4057 0.0579 0.2028 0.0153 0.2311 0.4565 0.7919 0.9355 0.3529 0.1987 0.7468 0.6068 0.0185 0.9218 0.9169 0.8132 0.6038 0.4451 0.4860 0.8214 0.7382 0.4103 0.0099 0.2722 0.9318 0.8913 0.4447 0.1763 0.8936 0.1389 0.1988 0.4660 (R > 0.3) & (R < 0.9) ans = 0 1 1 1 0 0 0 0 1 1 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1

## 4.6. Example III

Find those elements of array R that are greater than the scalar value of 40:

R = rand(3,5) * 50 R = 47.5065 24.2991 22.8234 22.2352 46.0906 11.5569 44.5649 0.9252 30.7716 36.9104 30.3421 38.1048 41.0704 39.5969 8.8133 R > 40 ans = 1 0 0 0 1 0 1 0 0 0 0 0 1 0 0