lecture 15 practice & exploration subfunctions: functions within functions “guessing game”:...
TRANSCRIPT
Lecture 15Lecture 15Practice & exploration Practice & exploration
Subfunctions: Functions within Subfunctions: Functions within functionsfunctions
““Guessing Game”: A hands-on Guessing Game”: A hands-on exercise in evolutionary exercise in evolutionary
designdesign
© 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Application of the tools in Application of the tools in MATLABMATLAB
The programming tools investigated in The programming tools investigated in this course are, of course, intended to this course are, of course, intended to be combined in your computer be combined in your computer programs to solve your technical programs to solve your technical computing problems.computing problems.
When you, as an engineer or scientist, When you, as an engineer or scientist, need to write a program in MATLAB to need to write a program in MATLAB to accomplish a technical computing task, accomplish a technical computing task, the more you learn about MATLAB the the more you learn about MATLAB the better; we have only touched the better; we have only touched the surface of the capabilities of MATLAB! surface of the capabilities of MATLAB!
SubfunctionsSubfunctions
SubfunctionsSubfunctions are functions that are used by are functions that are used by other functions. They allow you to separate other functions. They allow you to separate tasks within your programs.tasks within your programs.
Subfunctions are often used as “utility Subfunctions are often used as “utility functions” to perform calculations within a functions” to perform calculations within a main function.main function.
Another use for subfunctions is printing Another use for subfunctions is printing values to the command window. This is used values to the command window. This is used to separate the mathematical tasks of a to separate the mathematical tasks of a function from the print-statement output function from the print-statement output tasks.tasks.
m = m = mean_ex(a,imean_ex(a,i););
endend
fprintf('Meanfprintf('Mean is %f.', m);is %f.', m);
a(ia(i) = rand();) = rand();endend
rand('seedrand('seed', 5);', 5);
for (i = 1:1:100)for (i = 1:1:100)
function m = function m = mean_ex(a,imean_ex(a,i))
m = m = sum(a)/isum(a)/i;;
endend
function function sub_exsub_ex()()
Example of subfunctionsExample of subfunctions
Mean is 0.4531.Mean is 0.4531.
Consider writing a function that calculates the Consider writing a function that calculates the mean mean of a set of random numbers. You can write a of a set of random numbers. You can write a function to function to generate the random numbers and a subfunction generate the random numbers and a subfunction to to calculate their mean as follows:calculate their mean as follows:
Guessing Game ExerciseGuessing Game Exercise
In this exercise you are going to combine In this exercise you are going to combine many of the concepts you have learned to many of the concepts you have learned to build a guessing game function.build a guessing game function.
The approach taken in this exercise is The approach taken in this exercise is exploratory. MATLAB is used like a note exploratory. MATLAB is used like a note pad to explore the development of a pad to explore the development of a game.game.
Initially the game we design will be very Initially the game we design will be very simple; the design will evolve by re-simple; the design will evolve by re-building it in attempts to enhance its building it in attempts to enhance its capabilities.capabilities.
function guess()function guess()secret = 2;secret = 2;
fprintf('Yourfprintf('Your guess was %d. The secret guess was %d. The secret number was %number was %d.d.\\nn', guess, secret);', guess, secret);
guess = guess = input('Enterinput('Enter a guess: ');a guess: ');
Initial designInitial design
The initial game: A “secret number” will The initial game: A “secret number” will be hard-coded into the function. It will be hard-coded into the function. It will prompt the user for a guess and indicate prompt the user for a guess and indicate whether it is or is not the secret number.whether it is or is not the secret number.
Sample runSample run
This game is not very interactive (of course); weThis game is not very interactive (of course); we
only guess once before the game ends. Also, only guess once before the game ends. Also,
the game does not check to see if the guessthe game does not check to see if the guess
was too high, too low, or correct. We canwas too high, too low, or correct. We can
add code to extend the tool to accomplish this.add code to extend the tool to accomplish this.
Enter a guess: 3Enter a guess: 3Your guess was 3. The secret number was 2.Your guess was 3. The secret number was 2.
if guess > secretif guess > secret
fprintf('Toofprintf('Too highhigh\\n');n');
elseifelseif guess < secretguess < secret
fprintf('Toofprintf('Too lowlow\\n');n');
elseelse
fprintf('Correctfprintf('Correct\\nn');');
endend
Adding if statementsAdding if statements
Add the following set of if statements Add the following set of if statements so that the game tells the user if the so that the game tells the user if the guess is too high, too low, or correct.guess is too high, too low, or correct.
Sample runSample run
Enter a guess: 4Enter a guess: 4Too highToo highYour guess was 4. The secret number was 2.Your guess was 4. The secret number was 2.
The guessing game now tells the user if the The guessing game now tells the user if the guess is too high or too low. However, it guess is too high or too low. However, it allows only one guess. Add a while loop to allows only one guess. Add a while loop to allow for multiple guesses until the guess is allow for multiple guesses until the guess is correct.correct.
%Set secret number and get initial guess%Set secret number and get initial guess
while guess ~= secretwhile guess ~= secret
%If statements for determining if guess is too high/low%If statements for determining if guess is too high/low
%Get new guess%Get new guess
endend
%Print out that user guessed correctly%Print out that user guessed correctly
Adding a Adding a whilewhile loop loop The following modification lets the user The following modification lets the user
guess until the secret number is found:guess until the secret number is found:
Sample runSample run
Enter a guess: 1Enter a guess: 1Too lowToo lowEnter a guess: 5Enter a guess: 5Too highToo highEnter a guess: 4Enter a guess: 4Too highToo highEnter a guess: 3Enter a guess: 3Too highToo highEnter a guess: 2Enter a guess: 2Correct!Correct!
The game is more The game is more interactive now. interactive now. However, we always However, we always know that the right know that the right answer is two. Now add answer is two. Now add a randomly generated a randomly generated number as the secret number as the secret number.number.
secret = rand();secret = rand();
Adding random numbersAdding random numbers
Replace the hard-coded secret number Replace the hard-coded secret number with the following line; this is intended with the following line; this is intended to give a randomly generated secret to give a randomly generated secret number:number:
This will not do the trick for the reasons This will not do the trick for the reasons described next.described next.
Random number generatorRandom number generator
The The rand()rand() function generates function generates random numbers from 0 to 1. Used random numbers from 0 to 1. Used appropriately, we can determine appropriately, we can determine random numbers of an size. This is random numbers of an size. This is illustrated next.illustrated next.
Adding random integersAdding random integers
The following formula generates random The following formula generates random numbers over a range from “low” to “high”:numbers over a range from “low” to “high”:
secret = (high – low)*rand() + lowsecret = (high – low)*rand() + low
Then we need to round the random number Then we need to round the random number for the game, so that we have an integer for the game, so that we have an integer instead of a decimal number:instead of a decimal number:
secret = round((high – low)*rand() + low)secret = round((high – low)*rand() + low)
Let us set the limits of the game to a guess Let us set the limits of the game to a guess of an integer from 1 to 100.of an integer from 1 to 100.
Sample runSample runEnter a guess: 50Enter a guess: 50Too highToo highEnter a guess: 25Enter a guess: 25Too lowToo lowEnter a guess: 37Enter a guess: 37Too lowToo lowEnter a guess: 45Enter a guess: 45Too lowToo lowEnter a guess: 49Enter a guess: 49Too highToo highEnter a guess: 48Enter a guess: 48Too highToo highEnter a guess: 47Enter a guess: 47Correct!Correct!
ExercisesExercises
Add lines to your guessing game to Add lines to your guessing game to keep track of the number of guesses keep track of the number of guesses it took to get the right answer. Also, it took to get the right answer. Also, add a subfunction with input add a subfunction with input parameters to allow the user to pick parameters to allow the user to pick a new range of integers from which a new range of integers from which to guess.to guess.
SummarySummary
In this lecture we learned how to use In this lecture we learned how to use subfunctions within functions. subfunctions within functions.
In this lecture we learned to use In this lecture we learned to use MATLAB as a notepad to develop MATLAB as a notepad to develop ideas and code that uses the random ideas and code that uses the random number capability of MATLAB.number capability of MATLAB.
Remark: This exploratory work ould Remark: This exploratory work ould play important roles in the step of the play important roles in the step of the program design procedure via the program design procedure via the Structure PlanStructure Plan