Lesson 07: Logical Functions and Selection Structures
Objectives
 To understand how MATLAB interprets relational and logical operators.
 Understand the appropriate uses of the if/else family of cimmands
 Understand the switch/case structure
Background
7.1 Logical Operators
Relationship Operators
Relational operators compare operands quantitatively, using operators like "less than", "greater than", and "not equal to". The result of a relational comparison is a logical array indicating the locations where the relation is true.
These are the relational operators in MATLAB:
Syntax  Function Equivalent  Description 

A < B  lt(A,B)  Less thean 
A <= B  le(A,B)  Less than or equal to 
A > B  gt(A,B)  Greater than 
A >= B  ge(A,B)  Greater than or equal to 
A == B  eq(A,B)  Equal to 
A ~= B  ne(A,B)  Not equal to 
Numeric Comparison
The relational operators perform elementwise comparisons between two arrays. The arrays must have compatible sizes to facilitate the operation. For more information, see Compatible Array Sizes for Basic Operations.
Compare two matrices of the same size, the result is a logical matrix of the same size with elements indicating where the relation is true.
>> A = [2 4 6; 8 10 12];
>> B = [5 5 5; 9 9 9];
>> A < B
ans =
1 1 0
1 0 0
You also can compare one of the array to a scale.
>> A > 7
ans =
0 0 0
1 1 1
If you compare a 1×N row vector to an M×1 column vector, then MATLAB expands each vector into an M×N matrix before performing the comparison. The resulting matrix contains the comparison result for each combination of elements in the vectors.
>> A >= B
ans =
0 1 1
0 0 1
Empty Arrays
If one array has a dimension size of zero, then the size of the corresponding dimension in the other array must be 1 or zero, and the size of that dimension in the output is zero.
>> A = ones(3,0);
>> B = ones(3,1);
>> A == B
ans = Empty matrix: 3by0
Complex Numbers
 The operators >, <, >=, and <= use only the real part of the operands in performing comparisons.
 The operators == and ~= test both real and imaginary parts of the operands.
Inf, NaN, NaT, and undefined Element Comparisons
 Inf values are equal to other Inf values.
 NaN values are not equal to any other numeric value, including other NaN values.
 NaT values are not equal to any other datetime value, including other NaT values.
 Undefined categorical elements are not equal to any other categorical value, including other undefined elements.
Logic Statements
Use relational operators in conjunction with the logical operators A & B (AND), A  B (OR), xor(A,B) (XOR), and ~A (NOT), to string together more complex logical statements.
For example, you can locate where negative elements occur in two arrays.
>> A = [2 1; 3 10];
>> B = [0 2; 3 1];
>> A<0 & B<0
ans =
0 1
1 0
Logical Operators
There are two types of the logical operator in MATLAB:
Elementwise Operators
Elementwise operators perform a logical operation of array A and B and return an array containing elements set to either logical 1 (TRUE) or logical 0 (FALSE).
Syntax  Description 

A & B and(A, B) 
Elementwise logical AND 
A  B or(A, B) 
Elementwise logical OR 
~ A not(A) 
Logical NOT 
xor(A, B)  Logical ExclusiveOR 
ShortCircuit Logical Operators
ShortCircuit operators perform the logical operations of scalar a and b.
Syntax  Description 

a && b  ShortCircuit Logical AND 
a  b  ShortCircuit Logical OR 
This is a "shortcircuit" operation in that MATLAB evaluates b only if the result is not fully determined by a. For example: (ab), if a equals 1, then the entire expression evaluates to logical 1 (TRUE), regardless of the value of b. Under these circumstances, there is no need to evaluate b because the result is already known.
Use Scalar Logical Conditions
Create two vectors.
X = [1 0 0 1 1];
Y = [0 0 0 0 0];
Using the shortcircuit OR operator with X and Y returns an error. The shortcircuit operators operate only with scalar logical conditions.
Use the any and all functions to reduce each vector to a single logical condition.
any(X)  all(Y)
ans = logical
1
The expression is equivalent to 1 OR 0, so it evaluates to logical 1 (true) after computing only the first condition, any(X).
Specify Dependent Logical Conditions
Specify a logical statement where the second condition depends on the first. In the following statement, it doesn't make sense to evaluate the relation on the right if the divisor, b, is zero.
>> b = 0; a = 20;
>> x = (b ~= 0) && (a/b > 18.5)
x = logical
0
The result is logical 0 (false). However, if (b ~= 0) evaluates to false, MATLAB assumes the entire expression to be false and terminates its evaluation of the expression early. Therefore, MATLAB doe not need to evaluate the second part of the expression, which would result in an Inf value.
Specify b = 1 and evaluate the same expression.
>> b = 1; a = 20;
>> x = (b ~= 0) && (a/b > 18.5)
x = logical
1
The result is logical 1 (true). The first statement evaluates to logical 1 (true), MATLAB continues to evaluate the second part of the expression.
Locate Nonzero Values
Find the logical AND of two matrices. The result contains logical 1 (true) only where both matrices contain nonzero values.
>> A = [5 7 0; 0 2 9; 5 0 0];
>> B = [6 6 0; 1 3 5; 1 0 0];
>> A & B
ans = 3x3 logical array
1 1 0
0 1 1
1 0 0
Find the logical OR of two matrices. The result contains logical 1 (true) where either matrix contains a nonzero value. The zeros in the result indicate spots where both arrays have a value of zero.
>> A = [5 7 0; 0 2 9; 5 0 0];
>> B = [6 6 0; 1 3 5; 1 0 0];
>> A  B
ans = 3x3 logical array
1 1 0
1 1 1
1 0 0
Truth Tables
Create a truth table for and.
>> A = [true false]
A = 1x2 logical array
1 0
>> B = [true; false]
B = 2x1 logical array
1
0
>> C = A&B
C = 2x2 logical array
1 0
0 0
Create a truth table for or.
>> A = [true false]
A = 1x2 logical array
1 0
>> B = [true; false]
B = 2x1 logical array
1
0
>> C = AB
C = 2x2 logical array
1 1
1 0
7.2 Logical Functions
Function all
Determine if all array elements are nonzero or true.
Syntax  Description 

B = all(A)  Tests along the first array dimension of A whose size does not equal 1 and determines if the elements are all nonzero or logical 1 (true). In practice, all is a natural extension of the logical AND operator.

B = all(A,'all')  Tests over all elements of A. 
B = all(A,dim)  Tests elements along dimension dim. The dim input is a positive integer scalar. 
B = all(A,vecdim)  Tests elements based on the dimensions specified in the vector vecdim. For example, if A is a matrix, then all(A,[1 2]) tests over all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2. 
Test Matrix Columns (all)
Create a 3by3 matrix, and then test each column for all nonzero elements.
>> A = [0 0 3; 0 0 3; 0 0 3]
A = 3x3
0 0 3
0 0 3
0 0 3
>> B = all(A)
B = 1x3 logical array
0 0 1
Reduce a Logical Vector to a Single Condition (all)
Create a vector of decimal values and test which values are less than 0.5.
>> A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69];
>> B = (A < 0.5)
B = 1x7 logical array
0 0 1 1 1 1 0
The output is a vector of logical values. The all function reduces such a vector of logical values to a single condition.
>> C = all(A < 0.5)
C = logical
0
Test Arrays of Any Dimension (all)
Create a 3×7×5 multidimensional array and test to see if all of its elements are less than 3.
>> A = rand(3,7,5) * 5;
>> B = all(A(:) < 3)
B = logical
0
You can also test the array for elements that are greater than zero.
B = all(A(:) > 0)
B = logical
1
The syntax A(:) turns the elements of A into a single column vector, so you can use this type of statement on an array of any size.
Test Matrix Rows (all)
Create a 3by3 matrix.
>> A = [0 0 3; 0 0 3; 0 0 3]
A = 3×3
0 0 3
0 0 3
0 0 3
Test the rows of A for all nonzero elements by specifying dim = 2.
>> B = all(A,2)
B = 3×1 logical array
0
0
0
 all(A,1) works on successive elements in the columns of A and returns a row vector of logical values.
 all(A,2) works on successive elements in the rows of A and returns a column vector of logical values.
Function any
Determine if any array elements are nonzero
Syntax  Description 

B = any(A)  tests along the first array dimension of A whose size does not equal 1 and determines if any element is a nonzero number or logical 1 (true). In practice, any is a natural extension of the logical OR operator.

B = any(A,'all')  Tests over all elements of A. 
B = any(A,dim)  Tests elements along dimension dim. The dim input is a positive integer scalar. 
B = any(A,vecdim)  Tests elements based on the dimensions specified in the vector vecdim. For example, if A is a matrix, then any(A,[1 2]) tests over all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2. 
Test Matrix Columns (any)
Create a 3by3 matrix.
>> A = [0 0 3; 0 0 3; 0 0 3]
A = 3×3
0 0 3
0 0 3
0 0 3
Test each column for nonzero elements.
B = any(A)
B = 1×3 logical array
0 0 1
Reduce a Logical Vector to a Single Condition (any)
Create a vector of decimal values and test which values are less than 0.5.
>> A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69];
>> B = (A < 0.5)
B = 1×7 logical array
0 0 1 1 1 1 0
The output is a vector of logical values. The any function reduces such a vector of logical values to a single condition.
>> B = any(A < 0.5)
B = logical
1
Test Arrays of Any Dimension (any)
Create a 3by7by5 multidimensional array and test to see if any of its elements are greater than 3.
>> A = rand(3,7,5) * 5;
>> B = any(A(:) > 3)
B = logical
1
You can also test the array for elements that are less than zero.
>> B = any(A(:) < 0)
B = logical
0
The syntax A(:) turns the elements of A into a single column vector, so you can use this type of statement on an array of any size.
Test Matrix Rows (any)
Function find
Syntax  Description 

k = find(X)  Returns a vector containing the linear indices of each nonzero element in array X.

k = find(X,n)  Returns the first n indices corresponding to the nonzero elements in X. 
k = find(X,n,direction)  Where direction is 'last', finds the last n indices corresponding to nonzero elements in X. The default for direction is 'first', which finds the first n indices corresponding to nonzero elements. 
[row,col] = find(__)  Returns the row and column subscripts of each nonzero element in array X using any of the input arguments in previous syntaxes. 
[row,col,v] = find(__)  Also returns vector v, which contains the nonzero elements of X. 
Zero and Nonzero Elements in Matrix
$X = \left[ {\matrix{
1 & 0 & 2 \cr
0 & 1 & 1 \cr
0 & 0 & 4 \cr} } \right]$
Find the nonzero elements in a 3×3 matrix.
>> k = find(X)
k = 5×1
1
5
7
8
9
Use the logical not operator on X to locate the zeros.
>> k2 = find(~X)
k2 = 4×1
2
3
4
6
Elements Satisfying a Condition
>X = magic(4)
\(X = \left[ {\matrix{ {16} & 2 & 3 & {13} \cr 5 & {11} & {10} & 8 \cr 9 & 7 & 6 & {12} \cr 4 & {14} & {15} & 1 \cr } } \right]\)
Find the first five elements that are less than 10 in a 4×4 magic square matrix.
>> k = find(X<10,5)
k = 5×1
2
3
4
5
7
View the corresponding elements of X.
>> X(k)
ans = 5×1
5
9
4
2
7
To find the applicants who must at least 66" tall.
Consider the following list of applicant heights.
>> height = [63, 67, 65, 72, 69, 78, 75];
Find the index numbers of the elements that meet the criterion by using find function:
>> accept = find(height >= 66)
accept = 2 4 5 6 7
Display the actual heights by using the index number to call each element.
>> height(accept)
ans = 67 72 69 78 75
Create a report using disp and fprintf functions:
>> disp('The following candidates meet the height requirement.');
>> fprintf('Candidate # %4.0f is %4.0f inches tall \n', [accept; height(accept)])
The following candidates meet the height requirement.
Candidate # 2 is 67 inches tall
Candidate # 4 is 72 inches tall
Candidate # 5 is 69 inches tall
Candidate # 6 is 78 inches tall
Candidate # 7 is 75 inches tall
Elements Satisfying Multiple Conditions
Find the first three elements in a 4×4 matrix that are greater than 0 and less than 10. Specify two outputs to return the row and column subscripts to the elements.
\(X = \left[ {\matrix{{18} & 3 & 1 & {11} \cr 8 & {10} & {11} & 3 \cr 9 & {14} & 6 & 1 \cr 4 & 3 & {15} & {21} \cr} } \right]\)
>> element=find(X>0 & X<10, 3);
>> [row,col]=find(X>0 & X<10, 3)
row = 3×1
2
3
4
col = 3×1
1
1
1
Using fprintf to create a readable report.
>> disp('The first 3 elements that are greater than 0 and less than 10')
>> fprintf('Number %d at row %d, column %d \n', [X(element),row,col]'
The first 3 elements that are greater than 0 and less than 10
Number 8 at row 2, column 1
Number 9 at row 3, column 1
Number 4 at row 4, column 1
7.3 Selection Structures
if statement
Syntax  Description 

if expression statements elseif expression statements else statements end 
if expression, statements, end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false. The elseif and else blocks are optional. The statements execute only if previous expressions in the if...end block are false. An if block can include multiple elseif blocks. 
switchcase statement
Syntax  Description 

switch switch_expression case case_expression statements case case_expression statements ... otherwise statements end 
switch switch_expression, case case_expression, end evaluates an expression and chooses to execute one of several groups of statements. Each choice is a case. 
The switch block tests each case until one of the case expressions is true. A case is true when:
 For numbers, case_expression == switch_expression.
 For character vectors, strcmp(case_expression,switch_expression) == 1.
 For objects that support the eq function, case_expression == switch_expression.
 For a cell array case_expression, at least one of the elements of the cell array matches switch_expression, as defined above for numbers, character vectors, and objects.
Compare Single Values
Display different text conditionally, depending on a value entered at the command prompt.
n = input('Enter a number: ');
switch n
case 1
disp('negative one')
case 0
disp('zero')
case 1
disp('positive one')
otherwise
disp('other value')
end
At the command prompt, enter the number 1.
positive one
Repeat the code and enter the number 3.
other value
Compare Against Multiple Values
Determine which type of plot to create based on the value of plottype. If plottype is either 'pie' or 'pie3', create a 3D pie chart. Use a cell array to contain both values.
x = [12 64 24];
plottype = 'pie3';
switch plottype
case 'bar'
bar(x)
title('Bar Graph')
case {'pie','pie3'}
pie3(x)
title('Pie Chart')
otherwise
warning('Unexpected plot type. No plot created.')
end
Questions
 Consider the following matrices:
\(x = \left[ {\matrix{1 & {10} & {42} & 6 \cr 5 & 8 & {78} & {23} \cr {56} & {45} & 9 & {13} \cr {23} & {22} & 8 & 9 \cr} } \right]\) \(y = \left[ {\matrix{ 1 & 2 & 3 \cr 4 & {10} & {12} \cr 7 & {21} & {27} \cr } } \right]\) \(z = \left[ {\matrix{ {10} & {22} & 5 & {13} \cr } } \right]\) Using singleindex notation, find the index numbers of the elements in each matrix that contain values greater than 10.
 Find the row and column numbers (sometimes called subscripts) of the elements in each matrix that contain values greater than 10.
 Find the values in each matrix that are greater than 10.
 Using singleindex notation, find the index numbers of the elements in each matrix that contain values greater than 10 and less than 40.
 Find the row and column numbers for the elements in each matrix that contain values greater than 10 and less than 40.
 Find the values in each matrix that are greater than 10 and less than 40.
 Using singleindex notation, find the index numbers of the elements in each matrix that contain values between 0 and 10 or between 70 and 80.
 Use the length command together with results from the find command to determine how many values in each matrix are between 0 and 10 or between 70 and 80.
 The ifelse statement is particularly useful in functions. Write and test a function for each of these problems, assuming that the input to the function is a scalar:
 Suppose the legal drinking age is 21 in your state. Write and test a function to determine whether a person is old enough to drink.
 Many rides at amusement parks require riders to be a certain minimum height. Assume that the minimum height is 48" for a certain ride. Write and test a function to determine whether the rider is tall enough.
 When a part is manufactured, the dimensions are usually specified with a tolerance. Assume that a certain part needs to be 5.4 cm long, plus or minus 0.1 cm (5.4 ± 0.1 cm). Write a function to determine whether a part is within these specifications.
 Unfortunately, the United States currently uses both metric and English units. Suppose the part in Question 2.c was inspected by measuring the length in inches instead of centimeters. Write and test a function that determines whether the part is within specifications and that accepts input into the function in inches.
 Many solidfuel rocket motors consist of three stages. Once the first stage burns out, it separates from the missile and the second stage lights. Then the second stage burns out and separates, and the third stage lights. Finally, once the third stage burns out, it also separates from the missile. Assume that the following data approximately represent the times during which each stage burns:
Stage 1 0–100 seconds
Stage 2 100–170 seconds
Stage 3 170260 seconds
Write and test a function to determine whether the missile is in Stage 1 flight, Stage 2 flight, Stage 3 flight, or free flight (unpowered).
 Use the switch/case structure to solve these problems:
 Create a program that prompts the user to enter his or her year in school — freshman, sophomore, junior, or senior. The input will be a string. Use the switch/case structure to determine which day finals will be given for each group — Monday for freshmen, Tuesday for sophomores, Wednesday for juniors, and Thursday for seniors.
 Create a program to prompt the user to enter the number of candy bars he or she would like to buy. The input will be a number. Use the switch/case structure to determine the bill, where
1 bar \(\$ 75\)
2 bars \(\$1.25\)
3 bars \(\$1.65\)
more than 3 bars = \(\$ 1.65 + \$ 0.30 * (number\,ordered  3)\)