UCL Department of Phonetics and Linguistics

# Lecture 5: Control Statements

## Objectives

By the end of the session you should:

q       know the form of conditional expressions

q       know how to use the if-then-else statement to execute statements conditionally.

q       know how to use the while statement to execute statements repetitively

q       know how to use the for statement to execute statements a fixed number of times

## Outline

1.      Conditional Expressions

We have seen a number of arithmetical expressions using operators such as +, – and *.  We can also create “logical” or “conditional” expressions using comparison and Boolean operators.  Such expressions always produce a numerical result that is either 1 for true expressions, or 0 for false expressions.  The comparison operators are ‘<’, ‘<=’, ‘==’, ‘>=’, ‘>’ and ‘~=’.  The Boolean operators are ‘&’ (and), ‘|’ (or), ‘~’ (not).  You can use parentheses to bracket expressions to force an evaluation order.  For example:

x=10;

y=20;

disp(x < y);                 % displays 1

disp(x <= 10);               % displays 1

disp(x == y);                % displays 0

disp((0 < x) & (y < 30));    % displays 1

disp((x > 10) | (y > 100));  % displays 0

disp(~(x > 10));             % displays 1

You can even perform logical operations on arrays.  The operations are performed cell-by-cell and the output is an array of logical values:

area=[ 1 4 9 16 25 36 ];

perimeter=[ 4 8 12 16 20 24 ];

disp(area < perimeter);      % displays 1 1 1 0 0 0

Finally, you can use a logical array to select elements from a numerical array.  Cells from the numerical array that match true values in the logical array are extracted.  Just use the logical array in the place of the subscript operator, e.g.:

disp(area(area < perimeter));              % displays 1 4 9

2.      If Statement

In the programs we have written so far, every statement is executed every time the program is run.  The conditional statement ‘if condition statement end’ only executes the statement if the condition evaluates to true.  The condition should be a logical expression evaluating to true or false.  For example:

if (x < 10)

disp(x);          % only displays x when x < 10

end

if ((0 < x) & (x < 100))

disp('OK');       % displays OK if x between 0 and 100

end

You can put more than one statement between the ‘if’ and the ‘end’.  You can choose between two courses of action with ‘if condition statement else statement end’ as in:

if ((0 < x) & (x < 100))

disp('OK');

else

disp('x contains invalid number');

end

You can build a chain of tests with ‘elseif’, as in:

if (n <= 0)

disp('n is negative or zero');

elseif (rem(n,2)==0)

disp('n is even');

else

disp('n is odd');

end

You can embed, or ‘nest’ statements, as in: (What function does this code calculate?)

if (a < b)

if (a < c)

disp(a);

else

disp(c);

end

else

if (b < c)

disp(b);

else

disp(c);

end

end

The indenting of nested statements is not necessary but is recommended.

3.      While Statement

The ‘if’ statement allows us to execute a statement conditional on some logical expression.  The ‘while’ statement adds repetitive execution to the ‘if’ statement.  The format of the while statement is ‘while condition statement end’ and the statement is repeatedly executed while it is the case that the condition evaluates as true.  In other words the statement is executed over and over again until the condition becomes false.  Be warned that an error in such a statement might lead to your program looping continuously.  If your program is looping, press [Ctrl/c] in the command window to cancel it.  The while statement is useful when you do not know in advance how many times an operation needs to be performed.  For example, this code finds the smallest power of two which is larger than the number n:

n=50;

p=1;

while (p < n)

p = 2 * p;

end

disp(p);       % displays 64

The break statement is sometimes useful to cancel a while loop in the middle of a number of statements:

while (1)

req = input('Enter sum or "q" to quit : ','s');

if (req==’q’)

break;

end

disp(eval(req));

end

4.      For Statement

The ‘for’ statement is useful when you do know how many times you want to repeat a statement.  It is just a special form of the while loop.  To execute a statement 10 times with a while loop would require statements such as;

i=1;

while (i<=10)

disp(i);

i = i + 1;

end

This can be written more succinctly with the for statement; its basic syntax is ‘for var=sequence statement end’.  For example, the loop above could be written:

for i=1:10

disp(i);

end

Note that in a for loop, the variable is set to each value in the sequence in turn and retains that value when it is referred to inside the loop.  You can create sequences with increments different to one in the usual way with ‘start:increment:stop’.  You can even loop through the values in an array.  For example:

for even=2:2:100 …

for primes=[ 2 3 5 7 11 13 17 19 23 ] …

For loops are executed efficiently without actually building an array from the sequence.  This means that a loop of 1 million repetitions doesn’t require an array of size one million.  You can use the break statement in for loops as well as in while loops.

"Getting Started: Flow Control" in MATLAB Help.

## Exercises

For these exercises, use the editor window to enter your code, and save your answers to files under your account on the central server. When you save the files, give them the file extension of ".m". To run functions, call them by name from the command window.

1.      Write a program (ex51.m) that asks the user for an age and then classifies the age according to the following scheme:

Error < 0 <= Baby < 1 <= Child < 13 <= Teenager < 18 <= Adult < 60 <= Senior < 120 <= Error

For example:

Enter an age: 25

2.      Print a Fahrenheit to Celsius Conversion table for each 5 degrees between 0 and 100 Fahrenheit (ex52.m).  Use the function FtoC() that you wrote in exercise 4.2. Make sure the table is nicely formatted with fixed field widths and column headers.

3.      Write a program (ex53.m) that asks for a series of numbers, ending in the value 0, and calculates the sum and the mean.  For example:

Enter a number (end in 0) : 5

Enter a number (end in 0) : 6

Enter a number (end in 0) : 7

Enter a number (end in 0) : 8

Enter a number (end in 0) : 0

4 numbers entered.  Sum=26.  Mean=6.5.

4.      Adapt the function sinewave.m (sinewave2.m) that you wrote in exercise 4.3 so that it accepts a variable number of arguments.  If the sample rate is not given assume 11025.  If the duration is not given assume 1 second.  If the frequency is not given assume 1000Hz.  For example:

sinewave2(500,0.5,16000);

sinewave2(250,1.5);

sinewave2(2000);

sinewave2;

5.      (Advanced) Write a function (mysort.m) that sorts a list of numbers into increasing size (this replicates the functionality of the built-in sort function).  A simple method for sorting a list is called an ‘insertion’ sort, and it works like this:

A.     note that a list of length 1 is already sorted.

B.     to add a single element to a sorted list: shift down by one place all those elements which are larger than the element to be inserted.

C.     insert the element in the gap at its correct position.

D.     repeat steps B and C for each element remaining to be added.

Test your function by sorting a list of random numbers.  (Hint: you will need a while loop inside a for loop).

6.      (Homework) Build a pitch perception tester.  In a loop play pairs of tones which differ in pitch by 64Hz, 32Hz, 16Hz, etc randomly assigning the higher pitch to the first or second position.  Get the user to say whether the higher tone was first or second.  If the user was correct move on to the next smaller frequency difference, else stop and print the frequency difference of the last successful attempt.