Control Structures


Control Structures

matlab



Flow in a program

A program can be shown to have a flow of control. Parts of it may be executed and others might not be. Execution order can vary. e.g. it depends on the inputs.

Conditional control flow

Normal flow of control program statements is sequential, i.e

statement —> statement —> statement

With conditional statements, the control flow can change depending on a condition, i.e.

  • condition 1true—>statement a
  • condition 1false—>statement b
if statement

The if statement is one way in which conditional control flow is implemented in Matlab, e.g.

a = input('Enter a number:');
if (a >= 0)
root = sqrt(a);
disp(['Square root = ' num2str(root)]);
else
disp(['Number is -ve, no square root']);
end

The else statement is optional. However depend on the value of a we can have two different outputs.

Comparison/logical operators
Relational   Logical  
== Equals to ~ NOT
~= Not equals to && AND
< Less than || OR
> Greater than    
<= Less than or equal to    
>= Greater than or equal to    

An example:

...
at_risk = false;
if (gender == 'm') && (calories > 2500)
at_risk = true;
end
if (gender == 'f') && (calories > 2000) at_risk = true;
end
...
Operator Precedence
Highest Precedence    
1 () Brackets
2 Matrix transpose
2 .^ Element-wise power
2 ^ Matrix Power
3 - + Unary plus and minus
3 ~ Logical not
4 .* Element-wise multiplication
4 ./ Element-wise division
4 * Matrix multiplication
4 / Matrix division
5 + Addition
5 Subtraction
6 : Colon Operator
7 < Less than
7 <= Less than or equal to
7 > Greater than
7 >= Greater than or equal to
7 == Equal to
7 ~= Not equal to
8 && Logical and
9 || Logical or
Lowest Precedence    

If we now evaluate a condition using these operator precedence rules. So gender == 'm' && calories > 2500 is equivalent to (gender == 'm') && (calories > 2500).

switch statement

Can be used to test a variable against multiple values, rather than using multiple if statements. Here is an example:

switch day
case {1,2,3,4,5}
    day_name = 'Weekday';
case {6,7}
    day_name = 'Weekend';
otherwise
end

Iteration statements

Iteration statements are an alternative way to alter the control flow of a program. They permit a statement (or statements) to be executed multiple times. Two types of iteration statement in Matlab:

  • for loops
  • while loops
for loops

for loops execute statement(s) a number of times. However the number of times must be known before the loop starts. e.g.

n = input('Enter number:'); f = 1;
if (n >= 0)
for i = 2:n
   f = f * i;
end
   disp(['Factorial of ' num2str(n) '=' num2str(f)]);
else
   disp(['Cannot compute factorial of -ve number']);
end
while loops

while loops also execute statement(s) a number of times. The number of times is determined by the condition, and need not be known in advance. e.g.

i = round(rand(1) * 9) % random integer between 0 and 9 guess = -1;
while (guess ~= i)
guess = input('Guess a number:');
if (guess == i)
   disp('Correct!');
else
   disp('Wrong, try again ...');
end
end

In general, use:

  • for – if you know the number of iterations at the beginning of the loop
  • while – if you don’t

Program efficiency

Often there are a number of different ways of implementing a program to solve a given problem. One way may be more efficient (i.e. run quicker) than another. Here is an example of a piece of code:

tic
nRands = 1000000;
for i=1:nRands
rand_array(i) = rand(1);
end
toc

The tic ... toc is an inbuilt function used to time the code lying in-between them. It takes a lot of time to generate an array of 1,000,000 random numbers. A way to improve the efficiency in this case is to allocate an entire array before the for loop starts. Now there is no time-consuming copying of memory blocks:

tic
nRands = 1000000;
rand_array = zeros(1,nRands);
for i=1:nRands
rand_array(i) = rand(1);
end
toc

Jump Statements

Jump statements unconditionally transfer control to another part of the program. There are two types of jump statement in Matlab:

  • break statement
  • continue statement
break statement

The break statement transfers control to after the immediately enclosing for or while loop:

total = 0;
while (true)
n = input('Enter number: ');
if (n < 0)
    disp('Finished!');
    break;
end
total = total + n;
end
disp(['Total = ' num2str(total)]);
continue statement

The continue statement transfers control to the next iteration of the immediately enclosing for or while loop:

total = 0;
for i = 1:10
n = input('Enter number: ');
if (n < 0)
    disp('Ignoring!');
    continue;
end
    total = total + n;
end
disp(['Total = ' num2str(total)]);

Note the nesting of control structures in the above example. To preserve program clarity it is often good to avoid excessive nesting.


return  link
Written by Tobias Whetton