Intro to MATLAB Unit 5: CONTROL FLOW

Contents

Conditional Statements for Flow Control

The relational and logical operations we discussed previously will be used as conditions for the flow of our programs:

if statement

The if statement analyzes the condition that is given to it. If the if condition is true then the code within the if "block" will be executed. Otherwise, that code will be skipped:

w = 5;
x = 0;
y = -12
z = 27

if x > z
    disp('In if #1')
end

if x*w && y + z
    disp('In if #2')
end

if y & ~(~w || x) || ~(y+z)
    disp('In if # 3')
end

else statement

acts as a catch-all after the if statement. If the if condition is false then the else block gets executed:

if x > 1
    disp('In the if')
else
    disp('In the else')
end

if x ~= (w && y)
    disp('In the if')
else
    disp('In the else')
end

elseif statement

specify multiple conditions within the same block (only one block is executed)

x=10;
if x > 1
    disp('In the if')
elseif x > 5
    disp('In the elseif x>5') % <- this will NEVER be executed
elseif x < 1
    disp('In the elseif')
else
    disp('In the else')
end

if w && ~x
    disp('In the if')
elseif z > w
    disp('In the elseif')
else
    disp('In the else')
end

switch statement

use a switch statement to compare the input and a set of variables only one of the cases is run, like an if statement

meal = 'pancakes';

switch meal
    case 'burritos'
        cals = 500;
    case 'pancakes'
        cals = 200;
    case 'meatloaf'
        cals = 400;
    case 'rocks'
        cals = 2;
    otherwise %nothing matches, similar to an else statment
        disp('WARNING: no known meal specified!')   % display error message
        cals = 0;
end

Nested if statements

It is also possible to have an if statement within an if statement:

if w && ~x
    disp('In if #1')
    if z > w
        disp('In nested if #1')
    elseif x+w > z
        disp('In nested if #2')
    else
        disp('In the nested else')
    end
elseif x > 1
    disp('In if #1')
else
    disp('In the else')
end

This form of using if statements is useful for checking multiple conditions. Each if statement is still evaluated independently, but one path will be taken from each if statement that is encountered. If the first condition of the outer if statement in the above example is false, the inner if statement is never encountered and will have no effect on the output.

General rules when using nested if statements:

Indentation is important with all if statements, but especially nested ones.

*Practice Problems!

if x > y && y > z
    disp('Point #1')
elseif x > y + z && z^2 ~= x
    disp('Point #2')
elseif z + y == x
    disp('Point #3')
else
    disp('Point #4')
end

%What is the output if x = 10, y = 6, and z = 4?
%What is the output if x = 12, y = 4, and z = 8?

Iterative Statements for Flow Control

If you want to execute the same pice of code multiple times you can do so using a loop. We will introduce for and while loops.

for Loop

for i = 1:10
    disp(i)
end

Anything look familiar? These loops use colon notation to specify the number of passes to make.

As long as i is <= 10, the loop repeats. i is called the loop variable. You can name it whatever you'd like (though i is a common choice).

Each pass through the loop is called an iteration. This loop ran 10 times so it has 10 iterations, once for each value of the loop variable.

Any valid : notation statement will work for loops, e.g.:

for i = 10:-2:1
    disp(i)
end

%Why did the loop end with i = 2 when we defined i from 10 to 1?

CAUTION: You shouldn't redefine your loop variable within a for loop. It is possible, but bad practice:

for i = 1:10
    i = i + 2;
    disp(i)
end

% Notice what happens when you attempt to change the loop variable
% within the loop. This can make things very confusing (and MATLAB
% will tell you so.) Check out this to find out what is going on:
for i = 1:10
    disp(i)
    i = i + 2;
    disp(i)
    disp('----------')
end

Since colon notation is just one way of representing a vector, you can also use vectors to assign specific values to the loop variable:

a = [5 -2 -9 10 100]

for i = a
    disp(i)
end

%Some simple examples:
last = 8;
x = 1;
for i = 2:last
    x = x * i
end

%What is the output of the above?

Notice that any variables or function values can be used to set the loop variable, just as with normal colon notation:

for i = 1:length(a)
    j(i) = a(i)^2 + 3*a(i) - 12
end

%We wanted to compute a function for all values within a vector, so we
% used i as an index to each value of our vector. In this way we broke
% the problem into smaller pieces.

Using the loop variable as an index to vectors and matrices is very common. We can visit each value of the vector/matrix using this method.

Another/easier way of doing the above: element-by-element operations

k = a.^2 + 3.*a - 12

%This is a good example of what loops are capable of, but in general
%the element-by-element operations of MATLAB are faster and should
%be used when possible.

parfor Loop (parallel computing toolbox)

A = rand(100,100)+eye(100);
num_iter = 10;      % increase num_iter and observe what happens to
                    % the elapsed time

disp('for loop:')
tic
for i = 1:num_iter
    inv(A);
end
toc

disp('parfor loop:')
tic
parfor i = 1:num_iter
    inv(A);
end
toc

while Loop

Kind of a combination between if statements and for loops: use a conditional expression to set the number of loops:

i = 0;
while i < 10
    disp(i)
    i = i + 1;
end

%Notice that the above could have been accomplished with a for loop:

for i = 1:10
    disp(i)
end

In fact most while loops can be written as a for loop. So what is the difference?

In general, for loops are used when you know how many times they must run. They have a fixed number of iterations. While loops are useful when you want a certain condition to be met, but don't necessarily know how many iterations it will take to get there. We'll see some examples soon.

CAUTION: Be careful when setting variables for a while loop.

Looks like I forgot something...

i = 0;
while i < 10
    disp(i)
end

That's an interesting condition... This loop will never exit!!

while 0==0
    disp('Endless!')
end

If this happens to you press Ctrl-C to tell MATLAB to stop.

When using while loops, changing the loop variable is not only possible, but usually required!

Take care to ensure that the conditional statement will return FALSE at some point...otherwise it will run indefinitely!

example_sinTolerance(pi/2,0.000001)
sin(pi/2)

Nested Loops

We've already seen examples of if statements nested within loops, but loops can be nested within each other as well:

a = [1 2 3; 4 5 6; 7 8 9]
for i = 1:3
    for j = 1:3
        b(i,j) = a(i,j)^3 + (1/2) * a(i,j) - 6
    end
end

We again used loop variables as an address. Since we are dealing with a matrix we needed two variables: one for the row (i), and one for the column (j).

The inner loop will run to completion before the outer loop updates its loop variable. How are we travelling through the matrix?

How many times did the loop run?

Once again this loop would be better solved by saying:

b = a.^3 + (1/2).*a - 6;

CAUTION: Nested loops increase runtime FAST: imagine if we had used a 100x100 matrix instead. How many times would the loop run?

a=10;
b=10;
A = matrixFunction(a,b);    % example function using a nested loop

Loop Implementation: Rules and Tips

Implemntation proceedure:

First, figure out what needs to be repeated. Typically you have a large goal in mind that is being broken into smaller parts. Figure out what those smaller parts are because those will go inside your loop.

Then, think about how many times it needs to run. The answer could be a number (10 times) or it could be dependant on something else (until the tolerance is met). Think about how this affects your choice between for and while loops. If you choose to write a while loop, figure out what your ending condition would be.

After this is done, write the body of the loop. If you're writing a while loop, verify that the ending condition will eventually be met.

Finally, look at the variables in your loop and make sure they are initialized properly. Each value needs to have some starting value that is appropriate for the work being done. These starting values typically go right before the loop definition (outside of the loop).

*Practice Problems!

Write the ouput of the following loops:

%%%%% Loop #1 %%%%%

for i = 1:2:10
  j = i * 2;
  k = j + i;
  disp(k)
end
%%%%% Loop #2 %%%%%

a = [-5 2 10 -3 7]
for i = 1:length(a)
  k = a(i);

  for j = 1:3
    k = k + (i * j);
  end

  disp(k)
end

Rewrite the above examples to use while loops instead of for loops.

Rewrite matrixFunction to use while loops instead of for loops.

The fibonacci sequence is defined as:

1, 1, 2, 3, 5, 8, ...

Write a function called fibonacci that takes in an integer n and returns the first n numbers of the sequence.

Lecture notes for CSE200 (Fall 2015) at Washington University in St. Louis by Marion Neumann (based on materials from Doug Shook).