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:
|
|
Contents
- DATA FOR THIS LESSON
- SETUP FOR LESSON 9
- EXAMPLE 1: Simulate tossing a coin (selection using if-else)
- EXAMPLE 2: Output the square roots of first 3 integers (simple for loop)
- EXAMPLE 3: Sum the square roots of the first 10 integers (accumulation using a for loop )
- EXAMPLE 4: Simulate tossing coin 50 times (for loop with selection and accumulation)
- EXAMPLE 5: Alternative implementation of coin toss simulation (vector indexing)
- EXAMPLE 6: Load the sleep diary data
- EXAMPLE 7: Output a message if any subjects awoke after 3:30 pm
- EXAMPLE 8: Output subject number and gender for subjects with at least 1 wake-up after 3:30 pm
- EXAMPLE 9: Output the subject number and gender of the first student in section 3 (break)
- EXAMPLE 10: Using find to perform same task as EXAMPLE 9
- EXAMPLE 11: Output sections that have subjects with late wake-ups (continue)
- EXAMPLE 12: Output a table of early wake-ups using a loop
- SUMMARY OF SYNTAX
DATA FOR THIS LESSON
| File | Description |
diaries.mat |
|
SETUP FOR LESSON 9
- Set the Current Directory to Z:\working\MATLAB\Lesson9. (You will need to make a new directory for Lesson9.)
- Copy the diaries.mat file from Lesson 10 or download diaries.mat from Blackboard.
- Create a new script called Lesson9Script.m. (Use File->New->Blank M-File from the main MATLAB menubar.) You will enter each of the examples in a new cell in this script.
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:
- toss - a value between 0 and 1 picked at "random" by the rand function
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:
- k - the "loop counter"
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:
- k - acts as the loop counter
- sumSqrts - variable holding the total of the square roots of the numbers from 1 to 10
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:
- k - acts as the loop counter
- numHeads - the number of heads that result from the tosses
- numTosses - variable holding number of tosses to simulate
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:
- numHeads - number of values that are less than or equal to 0.5
- randTosses - vector of random numbers simulating the tosses
- timesToTosses - variable holding the number of times to "toss"
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:
- bedTimes - an array with the bedtimes of individual students in the columns
- dayCaffeine - a logical array with columns indicating daytime caffeine use for individual students
- gender - a vector of strings containing 'male' or 'female' designations for each student
- nightCaffeine - a logical array with columns indicating caffeine use after 6 pm for individual students
- section - vector containing sections numbers of the individual studens
- toSleepMinutes - an array with the number of minutes to fall asleep each night for the individual students
- useAlarm - a logical array with indications of alarm use for individual students in the columns.
- wakeTimes - an array with the wake times of individual students in the columns.
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:
- lateWakeup - number of wake-up times that were after 3:30 pm
- wakeHours - array with the wake-up time of day for the diary data set
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:
- k - acts as the loop counter
- timesLate - number of times each subject awoke after 3:30 pm
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:
- k - acts as the loop counter
- sect3 - logical vector with 1's corresponding to students in section
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:
- pFirst - the index of the lowest numbered subject in section 3
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:
- averWake - average wake-up hour for the cohort members
- numLate - number of times each cohort member woke up late
- s - acts as the loop counter (looping over the sections)
- wakeHour - hour defining the threshold for a "late" wake-up
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:
- earlyWake- threshold for an "early" wake-up
- k - acts as the loop counter
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 |
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 |
Execute the statements only if the
expression has the value true (non-zero).
|
Two alternative selection:if expression |
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.