LESSON 9: Program control

FOCUS QUESTION: How can I execute different code depending on the data?

This lesson demonstrates how to execute different code depending on the situation.

In this lesson you will:
  • Learn how program control is useful for solving problems.
  • Use if-else to express alternative paths in code.
  • Use a for loop to repeat a block of code with different variables.
Silver Greek Dekadrachm from about 400 BC

Contents


DATA FOR THIS LESSON

File Description
diaries.mat
  • The data set contains contains sleep diary data for a cohort in MATLAB variables.
  • The arrays have a column for each person.
  • The vectors have an element for each person.
  • The values in column n correspond to the same person as the value in position n of each vector.
  • The file contains the following variables:
    • bedTimes - array of bed times in decimal-date format.
    • dayCaffeine - array of daytime caffeine indicators.
    • gender - vector of male/female gender designators.
    • nightCaffeine - array of evening caffeine indicators.
    • section - vector of section indicators. The possible section numbers are 0, 1, 2, and 3. Section 0 contains only a single instructor. The remaining values correspond to course section numbers.
    • toSleepMinutes - an array of number of minutes to fall asleep.
    • useAlarm - array of alarm use indicators.
    • wakeTimes - array of wakeup times in decimal-date format.
  • The data was originally gathered by students taking CS 1173 in the fall 2009 semester and anonymized and randomized to be unidentifiable.
  • The first column of each array represents the instructor's values, the rest of the columns represent individual students.
  • Diaries were recorded for 21 days (from September 23, 2009 to October 13, 2009).

SETUP FOR LESSON 9


EXAMPLE 1: Simulate tossing a coin (selection using if-else)

Create a new cell in which you type and execute:

    toss = rand(1, 1);            % Pick a value at random between 0 and 1
    if toss <= 0.5                % Test against the value 0.5
        fprintf('Tossed heads\n'); % Say its heads if toss is less 0.5
    else
        fprintf('Tossed tails\n'); % Say its tails if toss is less 0.5
    end;

You should see a one variable in your Workspace Browser:

You should also see a message of the following form in the Command Window. If you execute this cell multiple times you will get different messages.

Tossed tails


EXAMPLE 2: Output the square roots of first 3 integers (simple for loop)

Create a new cell in which you type and execute:

    for k = 1:3               % The loop index k takes values 1, 2, 3
      fprintf('sqrt(%g) = %g\n', k, sqrt(k));
    end;

You should see the following variable in the Workspace Browser:

You should also see the following output in the Command Window:

sqrt(1) = 1
sqrt(2) = 1.41421
sqrt(3) = 1.73205

In the space below: Write MATLAB code to print the squares of the numbers from 1 to 5, one per line with identifying messages.

Enter the code in this cell and execute it.


EXAMPLE 3: Sum the square roots of the first 10 integers (accumulation using a for loop )

Create a new cell in which you type and execute:

    sumSqrts = 0;               % Need a variable to accumulate sum
    for k = 1:10                % Loop over the values k = 1, 2, ... 10
      sumSqrts = sumSqrts + sqrt(k);  % Add the next sqrt root to total
    end;
    fprintf('Sum of square roots from 1 to %g is %g\n', k, sumSqrts);

You should see the following 2 variables in your Workspace Browser:

You should also see the following output in the Command Window:

Sum of square roots from 1 to 10 is 22.4683

In the space below: write MATLAB code to print the sum of the squares of the numbers from 1 to 10.

Enter the code in this cell and execute it.


EXAMPLE 4: Simulate tossing coin 50 times (for loop with selection and accumulation)

Create a new cell in which you type and execute:

    numTosses = 50;            % Number of times to toss the coin
    numHeads = 0;              % Need a variable to accumulate total heads
    for k = 1:numTosses        % Loop over the values k = 1, 2, ... numTosses
       if rand(1, 1) <= 0.5    % Add to head count if 'tossed a head'
           numHeads = numHeads + 1;
        end;
    end;
    fprintf('%g heads in %g tosses\n', numHeads, numTosses);

You should see the following 3 variables in your Workspace Browser:

You should also see output of the following form in the Command Window:

22 heads in 50 tosses


EXAMPLE 5: Alternative implementation of coin toss simulation (vector indexing)

Create a new cell in which you type and execute:

    timesToTosses = 50;                  % Number of times to toss the coin
    randTosses = rand(timesToTosses,1);  % Create vector of "tosses"
    numHeads = sum(randTosses <= 0.5);   % How many were heads?
    fprintf('%g heads in %g tosses\n', numHeads, numTosses);

You should see the following 3 variables in your Workspace Browser:

You should also see output of the following form in the Command Window:

25 heads in 50 tosses


EXAMPLE 6: Load the sleep diary data

Create a new cell in which you type and execute:

    load diaries.mat;                        % Load the sleep diaries

You should see the following 8 variables in the Workspace Browser:


EXAMPLE 7: Output a message if any subjects awoke after 3:30 pm

Create a new cell in which you type and execute:

    wakeHours = (wakeTimes - floor(wakeTimes))*24; % Calculate the wake-up hours
    lateWakeup = sum(sum(wakeHours > 15.5));       % How many late wake-ups?
    if  lateWakeup > 0                             % See if any late wake-ups
        fprintf('%g wake-ups after 3:30 pm\n', lateWakeup);
    end;

You should see the following 2 variables in your Workspace Browser:

You should also see the following output in the Command Window.

30 wake-ups after 3:30 pm

In the space below: write MATLAB code to print the number of wake-ups before 5 am.

Enter the code in this cell and execute it.


EXAMPLE 8: Output subject number and gender for subjects with at least 1 wake-up after 3:30 pm

Create a new cell in which you type and execute:

    timesLate = sum(wakeHours > 15.5);  % Times each subject woke up late
    fprintf('Subjects who had a least one wake-up after 3:30 pm:\n');
    for k = 1:length(timesLate)
        if timesLate(k) > 0
          fprintf('Subject %g: a %s with %g late wake-ups\n', ...
            k, gender{k}, timesLate(k));
        end;
    end;

You should see the following two variables in your Workspace Browser:

You should also see the following output in the Command Window.

Subjects who had a least one wake-up after 3:30 pm:
Subject 2: a female with 1 late wake-ups
Subject 7: a male with 1 late wake-ups
Subject 8: a female with 1 late wake-ups
Subject 40: a female with 1 late wake-ups
Subject 46: a male with 3 late wake-ups
Subject 66: a male with 1 late wake-ups
Subject 70: a female with 1 late wake-ups
Subject 71: a female with 1 late wake-ups
Subject 73: a female with 1 late wake-ups
Subject 86: a female with 5 late wake-ups
Subject 101: a male with 4 late wake-ups
Subject 118: a female with 3 late wake-ups
Subject 125: a male with 2 late wake-ups
Subject 134: a female with 3 late wake-ups
Subject 142: a female with 2 late wake-ups

In the space below: write MATLAB code to print the subjects with wake-ups before 5 am.

Enter the code in this cell and execute it.


EXAMPLE 9: Output the subject number and gender of the first student in section 3 (break)

Create a new cell in which you type and execute:

    sect3 = (section == 3);          % True (1) for subjects in section 3
    for k = 1:length(sect3)          % Here k = 1, 2, ... subject number
       if sect3(k)                   % If subject is in section 3
            fprintf('First subject in section 3 is a %s with subject number %g\n', ...
                gender{k}, k);
            break;                   % Get out of the loop, we done
       end;
    end;

You should see the following two variables in your Workspace Browser:

You should also see the following output in the Command Window:

First subject in section 3 is a female with subject number 2


EXAMPLE 10: Using find to perform same task as EXAMPLE 9

Create a new cell in which you type and execute:

    pFirst = find(section == 3, 1, 'first'); % Find position of first subject in section 3
    fprintf('First subject in section 3 is a %s with subject number %g\n', ...
                gender{pFirst}, pFirst);

You should see the following variable in your Workspace Browser:

You should also see the following output in the Command Window:

First subject in section 3 is a female with subject number 2


EXAMPLE 11: Output sections that have subjects with late wake-ups (continue)

Create a new cell in which you type and execute:

    wakeHour = 12;                     % Wake hour to check
    averWake = mean(wakeHours);        % Compute the average wake up time for all subjects
    for s = 0:3                         % Check each section (0, 1, 2, 3)
       sectWake = averWake(section==s); % Pick out wakeups for section s
       numLate = sum(sectWake >= wakeHour);   % How many are after wakeHour?
       if numLate == 0                  % Skip this section if no late ones
           continue;
       end;
       fprintf('Section %g has %g subjects with mean wake-up after %g\n', ...
               s, numLate, wakeHour);
    end;

You should see the following 4 variables in your Workspace Browser:

You should also see the following output in the Command Window:

Section 2 has 2 subjects with mean wake-up after 12
Section 3 has 3 subjects with mean wake-up after 12


EXAMPLE 12: Output a table of early wake-ups using a loop

Create a new cell in which you type and execute:

    earlyWake = 6;
    fprintf('\n\n\tEarly wake-ups\n');
    fprintf('Subj\tSect\tGender\tAver Wakeup\n');    % Print out a title
    for k = 1:length(averWake)           % Here k = 1, 2, ... subject number
       if averWake(k) >= earlyWake       % Skip subjects who awoke later
           continue;
       end;
       fprintf(' %g\t  %g\t%s\t  %g\n', k, section(k), gender{k}, averWake(k));
    end;

You should see the following 2 variables in your Workspace Browser:

You should also see the following output in the Command Window:


	Early wake-ups
Subj	Sect	Gender	Aver Wakeup
 32	  1	male	  5.87253
 91	  2	female	  5.50243
 140	  3	female	  5.68481

SUMMARY OF SYNTAX

MATLAB syntax Description
break Exits the innermost enclosing loop.
continue Goes to the next iteration of the innermost enclosing loop, skipping the remaining statements in this iteration.
The for loop:
for k = initval:endval
statements to execute each time
end;
Execute statements for each value of the loop variable k from initval to endval. Note: the loop variable k takes on a different value each time through the loop. You should not modify the loop variable inside the loop.
One alternative selection:
if  expression
statements
end;
Execute the statements only if the expression has the value true (non-zero).
Two alternative selection:
if  expression
statements1
else
statements2
end;
Execute statements1 when expression is true (non-zero). Otherwise, execute statements2.
ind = find(x, k, 'first') returns a vector of the positions of the first k non-zero positions in the vector x.
rand(k, j) Create an an array with k rows and j columns containing values that are uniformly distributed in (0, 1). The values appear to be statistically "random".
randi(n, 1, 1) Return a "random" integer between 1 and n.
randi(n, k, j) Return an array with k rows and j columns containing "random" integer between 1 and n.
sqrt(X) Returns an array whose elements are the square roots of the corresponding elements of X.


This lesson was written by Kay A. Robbins of the University of Texas at San Antonio and last modified on 31-Dec-2010. Please contact krobbins@cs.utsa.edu with comments or suggestions. The image is a photo of a silver Dekadrachm (Greek) from about 400 B.C. taken by Carl Malamud on 12/14/05 and available at http://commons.wikimedia.org/wiki/File:Ancient_Greek_Silver_Coin_%28Dekadrachm%29,_rev,_about_400_B.C.E..jpg.