2.5. Control Constructs

Reading Assignment

Please read sections 4.1 through 4.4 of Physical Modeling in MATLAB, by Allen B. Downey [DOWNEY11].

Here we continue to present MATLAB control constructs. Whereas, the for loop is considered a counting loop because the number of loop executions is predetermined; the constructs here are conditional. The selection of the code block to execute and, in the case of while loop, the number of executions is dependent on the evaluation of a logical, or boolean, expression. That is, an expression that can be said to be either true (1) or false (0).

2.5.1. Relational Operators

Relational operators evaluate the relationship between two items and return either a true or false verdict. We usually think of relation operators as comparing numeric values, but this is not always the case.

Operator Meaning
== Equal to each other (note: a == b NOT a = b)
~= Not equal
> Greater than
< Less than
<= Less than or equal
>= Greater than or equal

2.5.2. Logical Operators

Logical operators allow us to combine other boolean expressions to form one composite expression.

Operator Meaning Example
& – && AND a && b
| – || OR a || b
~ NOT ~a

Parenthesis, ( ), may also be used to control the order in which boolean expressions are evaluated.

2.5.3. Selection Statements

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

2.5.3.1. If Construct

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

if condition
    code block
end

2.5.4. If - Else

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

if condition
    code block 1
else
    code block 2
end

2.5.4.1. Eleseif

Selection between multiple code blocks is achieve 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

Note

Only one code block will run, even if mulptiple conditions are true. Consider 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

2.5.4.2. Switch - Case Construct

When the value of a variable determines which code to execute, a switch - case construct might be used.

switch( x )
    case value_1        % x == value_1
        code block 1
    case value_2        % x == value_2
        code block 2
    case value_3        % x == value_3
        code block 3
    otherwise           % x ~= value_1, value_2, or value_3
        code block 4
end

2.5.5. Example Selection Statements

The following example illustrates nested if constructs. It also demonstrates the input and error functions that are used for interacting with the user of the program.

loan = input('Enter the loan amount: ');

if loan >= 1e6
    error('This program is only for loans 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.5.6. While Loop

The while loop can execute a code block multiple times. But the continued running of the loop depends on a logical condition. While loops should be used instead of a for whenever the number of loop executions can not be pre-determined. This might because an algorithm needs to run a different number of times depending on the value of a variable, or because of interactions from users.

The loop will evaluate the condition and run if it is true. Each time after running the code block, the condition is re-evaluated for a possible additional run. Whenever the condition is false, the loop stops. while loops run zero or more times.

while condition
    code block
end

2.5.7. Example Control Constructs - sinc

MATLAB has an built-in constant called eps, which is the smallest, positive, non-zero value that can be noticed with addition. A fun illustration of a while loop is to find this value manually.

Then we will test an application of eps for preventing divide by zero errors. If done correctly, our sinc function should plot as a smooth curve with sinc(0) = 1.

%% Find myeps, our manual find of eps

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);

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

t = -10:0.1:10;
y = t;              % just create y array for efficiency sake
% This could be vectorized, but this 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')

2.5.8. Continue and Break

MATLAB, as well as most other programming languages, have two addition 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 normally placed inside an if construct that is there to catch special conditions.

2.5.8.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 evaluated again to either advance to the next loop iteration or exit the loop.

In the following pseudocode example, if the special_codition 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.5.8.2. Break

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

In the following pseudocode example, if the special_codition 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

Note

Now take a look at the Save Your Money homework, which we will discuss the design of in class.