2.6. Control Constructs

Here we continue to present MATLAB control constructs. Whereas, the for loop is considered a counting loop because the number of loop executions is set before the loop starts; the constructs here are conditional. The evaluation of a logical (Boolean) expression determines which code block to execute and, in the case of while loops, the number of executions. A logical expression is a statement that evaluates to either true (1) or false (0). To write logical expressions, we need relational and logical operators.

Relational operators compare the relationship between two items and return either a true or false verdict. For example, using variables x and y, we might write a logical expression to see if x is greater than y as x > y. We usually think of relational operators as comparing numeric values, but this is not always the case. For example, the alphabetical order of text strings could be compared as in Bob > Bill. The relational operators are listed below.

Operator

Meaning

==

Equal to each other (note: x == y NOT x = y)

~=

Not equal

>

Greater than

<

Less than

<=

Less than or equal

>=

Greater than or equal

Logical operators allow us to combine other logical expressions to form a composite expression. Here we are using the symbols a and b to represent individual logical expressions. Symbol a, for example, might represent x > y, and b might represent x > z, where x, y, and z are variables.

Operator

Meaning

Example

&&

AND

a && b

||

OR

a || b

~

NOT

~a

Use parentheses, ( ), to control the order in which logical expressions are evaluated.

Note that as soon as MATLAB determines if a statement is true or false, it stops evaluating. For example, if the logical expression is a && b and a is found to be false, then b is not evaluated because the overall statement will be false. Similarly, if the expression is a || b, b is not evaluated if a is true. We call this behavior short circuit evaluation.

2.6.1. Selection Statements

Selection statements determine which, if any, code will run.

2.6.1.1. If Construct

The code block runs if the logical condition of an if statement is true, and is skipped if the condition is false.

if condition
    code block
end

2.6.1.2. Else

Add an else statement to the if construct when an alternate code block should run when the condition is false.

if condition
    code block 1
else
    code block 2
end

2.6.1.3. Elseif

Selection between multiple code blocks is achieved with any number of elseif statements. The final else statement is optional. Its code block runs when all of the other logical condition statements are false.

if condition1
    code block 1
elseif condition2
    code block 2
elseif condition3
    code block 3
else
    code block 4
end

What is the output of the following code?

a = 1;
if a < 2
    disp(2)
elseif a < 3
    disp(3)
elseif a < 4
    disp(4)
else
    disp(1)
end

2.6.1.4. Switch–Case Construct

Switch is a multi-branching selection statement. The switching value can be a variable, expression, or function that evaluates to either a scalar (usually integer values) or a character vector. The code that executes follows the first case statement that matches the switching value. Notice that the third case statement uses brackets around two values to match either value. The code following the otherwise statement is run when none of the case statements match the switching value.

% switchExample.m, example of a switch statement
for x = 0:5
    switch x
        case 1
            disp('x = 1')
        case 2
            disp('x = 2')
        case {3, 4}
            disp('x = 3 or 4')
        otherwise
            disp('x is not between 1 and 4')
    end
end

2.6.1.5. Example Selection Statements

The example below illustrates a nested if construct. It also demonstrates the input and error functions used to interact with the program user. It determines the interest rate for a loan based on the loan amount. The program terminates with a message in the Command Window when the error function is called.

% File: ifElse.m
loan = input('Enter the loan amount: ');

if loan >= 1e6
    error('Loans must be less than one million dollars')
else
    if loan < 100
        rate = 0.08;
    elseif loan < 1000
        rate = 0.06;
    elseif loan < 10000
        rate = 0.05;
    elseif loan < 100000
        rate = 0.04;
    else
        rate = 0.03;
    end
    disp(['The interest rate is ',num2str(rate*100),'%.'])
end

2.6.2. While Loop

The while loop will execute a code block until the logical condition is false, so it may not run, run once, or run many times. Use a while loop instead of a for loop whenever the number of loop executions can not be pre-determined. The loop will evaluate the condition and run the code block if it is true. Each time after running the code block, the condition is re-evaluated for a possible additional run. The loop stops when the condition is false.

while condition
    code block
end

2.6.3. Example Control Constructs—sinc

MATLAB has a built-in constant called eps, which is the smallest, positive, nonzero value that can be noticed when added to the number 1. A fun illustration of a while loop is to find this value with a program. When we add a number to 1 and the computer thinks that the sum is 1, we have a number smaller than eps.

We will use our calculated myeps variable to prevent a divide by zero error. Our sinc function should plot a smooth curve at \(sinc(0) = 1\).

%  File: sinc1.m
%% Manually find eps (myeps) using a while loop,
%  then use myeps to prevent divide by zero and plot
%  the sinc function.

epsilon = 1;
while (1 + epsilon) ~= 1
    myeps = epsilon;
    epsilon = epsilon / 2;
end
fprintf('1 + %9.5g is the same as 1\n', epsilon)
fprintf('myeps = %9.5g\n', myeps);

%% Use myeps with a sinc function sinc(x) = sin(x)/x

t = -10:0.1:10;
y = t;          % Create y array for efficiency's sake.
% This could be vectorized, but the code illustrates a for
% loop and a selection statement.
for k = 1:length(t)
    if t(k) == 0
        x = myeps;  % prevent a divide by zero error
    else
        x = t(k);
    end
    y(k) = sin(x)/x;
end
plot(t, y)
title('Sinc Function')
Sinc function (sin(x)/x).

Fig. 2.4 Sinc function (\(\sin(x)/x\))

2.6.4. Continue and Break

MATLAB has two additional commands related to looping control constructs. These commands provide mechanisms for altering the execution flow in the middle of a loop. Both of these commands are typically placed inside an if construct that is there to catch special conditions.

2.6.4.1. Continue

The continue keyword causes execution of the current loop iteration to skip past the remainder of the loop’s code block. Control returns to the beginning of the loop where the loop condition is re-evaluated to either advance to the next loop iteration or exit the loop.

In the following pseudocode example, if the special_condition is true, code block 2 is skipped, and control moves back to evaluating loop_condition.

while loop_condition
    code block 1
    if special_condition
        continue
    end
    code block 2
end

2.6.4.2. Break

The break keyword causes execution of the current loop to stop. Control advances to the code after the loop.

In the following pseudocode example, if the special_condition is true, code block 2 is skipped, and the loop is finished.

while loop_condition
    code block 1
    if special_condition
        break
    end
    code block 2
end

2.6.4.3. Continue and Break Example

A short script program using continue and break statements is listed below. The program prompts the user to enter numbers one at a time. The user chooses how many numbers to enter. Since we don’t know how many numbers will be entered, the loop is programmed with a while true statement to run until the user enters a value of zero. The break statement stops the loop when zero is entered. If the user makes a mistake and enters a negative number, we don’t want to include that number in the average, so a continue statement skips the rest of the loop’s code and the user is prompted again.

% File: continueBreakDemo.m
% Prompt the user for the length of items and
% calculate the average.

disp('Enter item lengths, enter zero when finished')
sum = 0;
n = 0;
while true
    item_len = input("Enter the next length: ");
    if item_len == 0
        break;
    elseif item_len < 0
        disp('Items must have a length greater than 0.')
        continue;
    end
    n = n + 1;
    sum = sum + item_len;
end
average = sum/n;
disp(['The average length is ', num2str(average)])