Chapter 10
IN THIS CHAPTER
Adding decision-making to your scripts
Using recursive functions
Repeating tasks
Defining menus
The scripts and functions you have created so far have all performed a series of tasks, in order, one at a time. However, sometimes it’s important to skip steps or to perform the same step more than once. Humans make decisions about what to do with ease, but computers need a little help by using conditional statements that allow actions only when needed. Humans also know when to do something more than once, but computers need help in this regard as well, by using loop statements that define when and how many times to perform a task. This chapter helps you understand the use of both conditional and loop statements when creating scripts and functions.
As part of discovering how decisions are made and just how repetition works, you see two practical examples of how to employ your new skills. The first is a technique called recursion, which is simply a method of performing a task more than once, but in an elegant way. Using recursion makes solving some math problems significantly easier. The second involves the use of a menu. Most multifunction applications rely on menus to allow a user to select one option out of a number of possibilities.
Making Decisions
When you come to an intersection, you make a decision: go through or stop. If the light is red, you stop. However, when the light is green, you go through the intersection. The “if this condition exists, then do this” structure is something humans use almost constantly. In fact, we sometimes don’t think about it consciously at all. A decision is often made without conscious thought because we have made it so many times.
A computer needs guidance in order to make a decision. It lacks a subconscious and therefore needs to work through each decision. When working with MATLAB, you might need to tell the computer that if a value is above a certain level, the computer should perform a certain set of steps. Perhaps you need to compensate in the computation of a result (some factor has affected the result beyond the normal value) or you simply need to look at the formula in a different way. The decision could be procedural — a user selects a particular option and the computer needs to perform the associated task. The thing to remember about a computer is that it follows whatever you tell it precisely, so you need to provide precise decision-making instructions.
The following sections describe two different decision-making structures that MATLAB provides: the if statement and the switch statement. Each of these statements has a specific format as well as specific times when you’d use it.
Decision-making code has a number of terms associated with it. A statement simply indicates what the code should do. It’s the line of code that appears first in a block of tasks. A structure describes the statement and all the code that follows until the end keyword is reached. A condition specifies how to make the decision.
Using the if statement
The simplest decision to make is whether to do something — or not. However, you might need to decide between two alternatives. When a situation is true, you perform one task, but when it’s false, you perform another task. There are still other times when you have multiple alternatives and must choose a course of action based on multiple scenarios and using multiple related decisions. The following sections cover all these options.
Making a simple decision
Starting simply is always best. The if statement makes it possible to either do something when the condition you provide is true or not do something when the condition you provide is false. The following steps show how to create a function that includes an if statement. You can also find this function in the SimpleIf.m file supplied with the downloadable source code.
1. Click the arrow under the New entry on the Home tab of the MATLAB menu and select Function from the list that appears.
You see the Editor window that you used for the examples in Chapter 9.
2. Delete outputArg1,outputArg2.
The example doesn’t provide an output argument, but it does require an input argument.
3. Change the function name from Untitled toSimpleIf.
The primary function name must match the name of the file.
4. Change inputArg1,inputArg2 to Value.
The function receives a single value from the caller to use in the decision-making process.
5. Delete the existing function code.
6. Type the following code into the function between the comment and the end keyword.
if Value > 5
disp('The input value is greater than 5!');
end
This code makes a simple comparison. When the input argument, Value, is greater than 5, the function tells you about it. Otherwise, the function doesn’t provide any output at all.
7. Create or select the Chapter10 folder, if you haven’t done so already. Click Save.
You see the Select File for Save As dialog box. Notice that the File Name field has the correct filename entered for you. This is the advantage of changing the function name before you save the file for the first time.
8. Click Save in the Select File for Save As dialog box.
The function file is saved to disk.
9. Type SimpleIf(6) and press Enter in the Command Window.
You see the following output:
The input value is greater than 5!
10. Type SimpleIf(4) and press Enter in the Command Window.
The function doesn’t provide any output. Of course, this is the expected reaction.
Adding an alternative option
Many decisions that people make are choices between two options. For example, you might go to the beach today, or choose to stay home and play dominoes, based on whether it is sunny. When the weather is sunny, you go to the beach. MATLAB has a similar structure. The application chooses between two options based on a condition. The second option is separated from the first by an else clause — the application performs the first task, or else it performs the second. The following steps demonstrate how the else clause works. (These steps assume that you completed the SimpleIf example in the preceding section.) You can also find this function in the IfElse.m file supplied with the downloadable source code.
1. In the Editor window, with the SimpleIf.m file selected, click the down arrow under Save and choose Save As from the list that appears.
You see the Select File for Save As dialog box.
2. Type IfElse.m in the File Name field and click Save.
MATLAB saves the example using a new name.
3. Replace the SimpleIf function name with IfElse.
4. Add the following code after the disp() function call:
else
disp('The input value is less than 6!');
The function can now respond even when the primary condition isn’t met. When Value is greater than 5, you see one message; otherwise, you see the other message.
5. Click Save.
The function file is saved to disk.
6. Type IfElse(6) and press Enter in the Command Window.
You see the following output:
The input value is greater than 5!
7. Type IfElse(4) and press Enter in the Command Window.
You see the following output:
The input value is less than 6!
The example demonstrates that you can provide alternative outputs depending on what is happening within the application. Many situations arise in which you must choose an either/or type of condition.
Creating multiple alternative options
Many life decisions require more than two alternatives. For example, you’re faced with a menu at a restaurant and want to choose just one of the many delicious options. Applications can encounter the same situation. A user may select only one of the many options from a menu, as an example. The following steps show one method of choosing between multiple options. (The steps assume that you completed the IfElse example in the preceding section.) You can also find this function in the IfElseIf.m file supplied with the downloadable source code.
1. In the Editor window, with the IfElse.m file selected, click the down arrow under Save and choose Save As from the list that appears.
You see the Select File for Save As dialog box.
2. Type IfElseIf.m in the File Name field and click Save.
MATLAB saves the example using a new name.
3. Replace the IfElse function name with IfElseIf.
4. Add the following code after the first disp() function call:
elseif Value == 5
disp('The input value is equal to 5!');
At this point, the code provides separate handling for inputs greater than, equal to, and less than 5.
It’s possible to have an if…elseif statement that doesn’t include the else statement in it. In this case, every option would have a condition and there wouldn’t be any default code block, as you would have with the else statement.
5. Modify the third disp() function statement to read as follows:
disp('The input value is less than 5!');
Many people make the mistake of not modifying everything that needs to be modified by an application change. Because you now have a way of handling inputs equal to five, you must change the message so that it makes sense to the user. Failure to modify statements often leads to odd output messages that serve only to confuse users.
6. Click Save.
The function file is saved to disk.
7. Type IfElseIf(6) and press Enter in the Command Window.
You see the following output:
The input value is greater than 5!
8. Type IfElseIf(5) and press Enter in the Command Window.
You see the following output:
The input value is equal to 5!
9. Type IfElseIf(4) and press Enter in the Command Window.
You see the following output:
The input value is less than 5!
Using the switch statement
You can create any multiple alternative selection code needed by using the if…elseif statement. However, you have another good way to make selections. A switch statement lets you choose one of a number of options using code that is both easier to read and less time-consuming to type than using a lot of if…elseif statements. The result is essentially the same, but the method of obtaining the result is different. The following steps demonstrate how to use a switch statement. You can also find this function in the SimpleSwitch.m file supplied with the downloadable source code.
1. Click the arrow under the New entry on the Home tab of the MATLAB menu and select Function from the list that appears.
You see the Editor window.
2. Delete outputArg1,outputArg2.
The example doesn’t provide an output argument, but it does require an input argument.
3. Change the function name from Untitled toSimpleSwitch.
The primary function name must match the name of the file.
4. Change inputArg1,inputArg2 to Value.
The function receives a value from the caller to use in the decision-making process.
5. Delete the existing function code.
6. Type the following code into the function between the comment and the end keyword.
switch Value
case 1
disp('You typed 1.');
case 2
disp('You typed 2.');
case 3
disp('You typed 3.');
otherwise
disp('You typed an alternative value.');
end
This code specifically compares Value to the values provided. When Value matches a specific value, the application outputs an appropriate message.
At times, the input value doesn’t match the values you expect. In such cases, the otherwise clause comes into play. It provides the means for doing something even if the input wasn’t what you expected. If nothing else, you can use this clause to tell the user to input an appropriate value.
7. Click Save.
You see the Select File for Save As dialog box. Notice that the File Name field has the correct filename entered for you.
8. Click Save.
The function file is saved to disk.
9. Type SimpleSwitch(1) and press Enter in the Command Window.
You see the following output:
You typed 1.
10. Type SimpleSwitch(4) and press Enter in the Command Window.
You see the following output:
You typed an alternative value.
11. Type SimpleSwitch(-1) and press Enter in the Command Window.
You see the following output:
You typed an alternative value.
It’s important to note that the current code checks only for values of 1, 2, or 3. Consequently, the user could provide a negative number, even if you’re not expecting one. Later you discover how to check the input to ensure that it’s in the correct range.
12. Type SimpleSwitch('Hello') and press Enter in the Command Window.
You see the following output:
You typed an alternative value.
It’s easy to become focused on the input you’re expecting, rather than the input the user will provide. Not only do you have to check the range of incoming values, you must also check their data type to ensure that you’re not getting something like a string.
Understanding the switch difference
A switch provides a short method of making specific decisions. You can’t make a generalize decision, such as whether a value is greater than some amount. In order to make a match, the value must equal a specific value. The specific nature of a switch means that:
· The code you write is shorter than a comparable if…elseif structure with more than three alternatives.
· Others are better able to understand your code because it’s cleaner and more precise.
· The switch statement tends to produce focused code that avoids the odd mixing of checks that can occur when using the if…elseif structure.
· MATLAB is able to optimize the application for better performance because it doesn’t have to check a range of values.
· Using an otherwise clause can help ensure that people understand that you didn’t anticipate a particular value or that the value is less important.
Deciding between if and switch
Whenever possible, use a switch statement when you have more than three options to choose from and you can focus attention on specific options for just one variable. Using the switch statement has some significant advantages, as described in the preceding section.
The if statement provides you with flexibility. You can use it when a range of values is acceptable or when you need to perform multiple checks before allowing a task to complete. For example, when opening a file, you might need to verify that the file actually does exist, that the user has the required rights to access the file, and that the hard drive isn’t full. An if statement would allow you to check all these conditions in a single piece of code, making the conditions easier to see and understand.
When writing your own applications, you need to keep in mind that there isn’t a single solution to any particular problem. The overlap between the if and switch statements makes it clear that you could use either statement in many situations. Both statements would produce the same output, so there isn’t a problem with using them. However, if statements are better when flexibility is required, but switch statements are better when precision and speed are important. Choose the option that works best for a particular situation, rather than simply choosing an option that works.
Creating Recursive Functions
Many elegant programming techniques exist in the world, but none are quite as elegant as the recursive function. The concept is simple: You create a function that keeps calling itself until a condition is satisfied, and then the function delivers an answer based on the results of all those calls. This process of the function calling itself multiple times is known as recursion, and a function that implements it is a recursive function.
The most common recursion example is calculating factorial (n!), where n is a non-negative number (0! equals 1). (Calculating a factorial means multiplying the number by each number below it in the hierarchy. For example, 4! is equal to 4 * 3 * 2 * 1, or 24.)
Most examples that show how to create a recursive function don’t really demonstrate how the process works. The following steps help you create a recursive function that does demonstrate how the process works. Later in the chapter, you see a less involved version of the same code that shows how the function would normally appear. You can also find this function in the Factorial1.m file supplied with the downloadable source code.
1. Click the arrow under the New entry on the Home tab of the MATLAB menu and select Function from the list that appears.
You see the Editor window.
2. Change outputArg1,outputArg2 to Result.
The function returns a result to each preceding cycle of the call.
3. Change the function name from Untitled toFactorial1.
The primary function name must match the name of the file.
4. Change inputArg1,inputArg2 to Value, Level.
The Value received is always one less than the previous caller received. The Level demonstrates how Value is changing over time.
5. Delete the existing function code.
6. Type the following code into the function between the comment and the end keyword:
if nargin < 2
Level = 1;
end
if Value > 1
fprintf('Value = %d Level = %d\n', Value, Level);
Result = Factorial1(Value - 1, Level + 1) * Value;
disp(['Result = ', num2str(Result)]);
else
fprintf('Value = %d Level = %d\n', Value, Level);
Result = 1;
disp(['Result = ', num2str(Result)]);
end
This example makes use of an optional argument. The first time the function is called, Level won’t have a value, so the application automatically assigns it a value of 1.
The code breaks the multiplication task into pieces. For example, when Value is 4, the code needs to multiply it by 3 * 2 * 1. The 3 * 2 * 1 part of the picture is defined by the call to Factorial1(Value - 1, Level + 1). During the next pass, Value is now 3. To get the appropriate result, the code must multiply this new value by 2 * 1. So, as long as Value is greater than 1 (where an actual result is possible), the cycle must continue.
A recursive function must always have an ending point — a condition under which it won’t call itself again. In this case, the ending point is the else clause. When Value finally equals 1, Result is assigned a value of 1 and simply returns, without calling Factorial1() again. At this point, the calling cycle unwinds and each level returns, one at a time, until a final answer is reached.
Notice that this example uses a new function, fprintf(), to display information onscreen. The fprintf() function accepts a formatting specification as its first input. In this case, the specification says to print the string Value =, followed by the information found in Value, then Level =, followed by the information found in Level. The %d in the format specification tells fprintf() to print an integer value. You use fprintf() as a replacement for disp() when the output formatting starts to become more complex. Notice that disp() requires the use of the num2str() function to convert the numeric value of Result to a string in order to print it.
7. Click Save.
You see the Select File for Save As dialog box. Notice that the File Name field has the correct filename entered for you.
8. Click Save.
The function file is saved to disk.
9. Type Factorial1(4) and press Enter in the Command Window.
You see the following output:
Value = 4 Level = 1
Value = 3 Level = 2
Value = 2 Level = 3
Value = 1 Level = 4
Result = 1
Result = 2
Result = 6
Result = 24
ans =
24
The output tells you how the recursion works. Notice that all the Value and Level outputs come first. The function must keep calling itself until Value reaches 1. When Value does reach 1, you see the first Result output. Of course, Result is also 1. Notice how the recursion unwinds. The next Result is 2 * 1, then 3 * 2 * 1, and finally 4 * 3 * 2 * 1.
Now that you have a better idea of how the recursion works, look at the slimmed-down version in Listing 10-1. You can also find this function in the Factorial2.m file supplied with the downloadable source code.
LISTING 10-1 A Method for Calculating n!
function [ Result ] = Factorial2( Value )
%Factorial2 - Calculates the value of n!
% Outputs the factorial value of the input number.
if Value > 1
Result = Factorial2(Value - 1) * Value;
else
Result = 1;
end
end
UNDERSTANDING THE FPRINTF() FORMAT SPECIFICATION
A format specification tells a function how to display information onscreen. The fprintf() function accepts a regular string as input for a format specification, reading each character. When fprintf() encounters a percent (%) character, it looks at the next character as a definition of what kind of formatted input to provide. The following list provides an overview of the % character combinations used to format information using fprintf().
· %bo: Floating point, double precision (Base 8)
· %bu: Floating point, double precision (Base 10)
· %bx: Floating point, double precision (Base 16, using lowercase letters for the numbers a through f)
· %bX: Floating point, double precision (Base 16, using uppercase letters for the numbers A through F)
· %c: Single character
· %d: Signed integer
· %e: Floating point, exponential notation using a lowercase e
· %E: Floating point, exponential notation using an uppercase E
· %f: Floating point, fixed point notation
· %g: Floating point, general notation using the more compact of %f or %e with no trailing zeros
· %G: Floating point, general notation using the more compact of %f or %E with no trailing zeros
· %i: Signed integer
· %o: Unsigned integer (Base 8)
· %s: String of characters
· %to: Floating point, single precision (Base 8)
· %tu: Floating point, single precision (Base 10)
· %tx: Floating point, single precision (Base 16, using lowercase letters for the numbers a through f)
· %tX: Floating point, single precision (Base 16, using uppercase letters for the numbers A through F)
· %u: Unsigned integer (Base 10)
· %x: Unsigned integer (Base 16, using lowercase letters for the numbers a through f)
· %X: Unsigned integer (Base 16, using uppercase letters for the numbers A through F)
When working with numeric input, you can also specify additional information between the % and the subtype, such as f for floating point. For example, %-12.5f would display a left-justified number 12 characters in width with 5 characters after the decimal point. See the full details of formatting strings at https://www.mathworks.com/help/matlab/matlab_prog/formatting-strings.html.
The final version is much smaller but doesn’t output any helpful information to tell you how it works. Of course, this version will run a lot faster, too.
Performing Tasks Repetitively
Giving an application the capability to perform tasks repetitively is an essential part of creating an application of any complexity. Humans don’t get bored performing a task once. It’s when the task becomes repetitive that true boredom begins to take hold. A computer can perform the same task in precisely the same manner as many times as needed because the computer doesn’t get tired. In short, the area in which computers can help humans most is performing tasks repetitively. As with decisions, you have two kinds of structures that you can use to perform tasks repetitively, as described in the sections that follow.
You see a number of terms associated with repetitive code. The same terms that you see used for decision-making code also apply to repetitive code. In addition, the term loop is used to describe what repetitive code does. A repetitive structure keeps executing the same series of tasks until such time as the condition for the repetition is satisfied and the loop ends.
Using the for statement
The for statement performs a given task a specific number of times, unless you interrupt it somehow. The examples in the “Making Decisions” section, earlier in this chapter, provide steps for creating functions. Listing 10-2 shows how to use a for loop in an example. You can also find this function in the SimpleFor.m file supplied with the downloadable source code.
LISTING 10-2 Creating Repetition Using the for Statement
function [ ] = SimpleFor( Times )
%SimpleFor: Demonstrates the for loop
% Tell the application how many times to say hello!
if nargin < 1
Times = 3;
end
for SayIt = 1:Times
disp('Howdy!')
end
end
In this case, SimpleFor() accepts a number as input. However, if the user doesn’t provide a number, then SimpleFor() executes the statement three times by default.
Notice how the variable, SayIt, is created by assigning it an initial value of 1 (the 1 in 1:Times) and used as the starting point for the loop. The range of 1:Times tells for to keep displaying the message Howdy! the number of times specified by Times. Every time the loop is completed, the value of SayIt increases by 1, until the value of SayIt is equal to Times. At this point, the loop ends.
Using the while statement
The while statement performs a given task until a condition is satisfied, unless you stop it somehow. The examples in the “Making Decisions” section of the chapter provide steps for creating functions. Listing 10-3 shows how to use a while loop in an example. You can also find this function in the SimpleWhile.m file supplied with the downloadable source code.
LISTING 10-3 Creating Repetition Using the while Statement
function [ ] = SimpleWhile( Times )
%SimpleWhile: Demonstrates the while loop
% Tell the application how many times to say hello!
if nargin < 1
Times = 3;
end
SayIt = 1;
while SayIt <= Times
disp('Howdy!')
SayIt = SayIt + 1;
end
end
In this example, the function can either accept an input value or execute a default number of times based on whether the user provides an input value for Times. The default is to say Howdy! three times.
Notice that the loop code actually begins by initializing SayIt to 1 (so the count begins at the right place). It then compares the current value of SayIt to Times. When SayIt is greater than Times, the loop ends.
You must manually update the counter variable when using a while loop. Notice that the line that adds 1 to SayIt after the call to disp(). If this line of code is missing, the application ends up in an endless loop — meaning that it never wants to end. If you accidentally create an endless loop, you can stop it by pressing Ctrl+C.
Starting a new loop iteration using continue
There are times when you won’t want to perform any processing should certain events occur, such as a value you don’t really need. However, you don’t want to stop the processing as a whole — you only want to stop this particular iteration of the loop. The continue clause makes it possible to end the current iteration and move on to the next loop iteration.
Listing 10-4 shows how to use the continue clause with a while loop, but you can use it precisely the same way with the for loop. The examples in the “Making Decisions” section, earlier in the chapter, provide steps for creating functions. You can also find this function in the UsingContinue.m file supplied with the downloadable source code.
LISTING 10-4 Using the continue clause
function [ ] = UsingContinue( Times )
%UsingContinue: Demonstrates the while loop
% Tell the application which iterations to process.
% Iteration five displays a special message.
if nargin < 1
Times = 3;
end
SayIt = 1;
while SayIt <= Times
if SayIt == 5
disp('Welcome to iteraction 5!')
SayIt = SayIt + 1;
continue;
end
disp('Howdy!')
SayIt = SayIt + 1;
end
end
The code executes precisely the same way that the SimpleWhile example works, except that this version contains an additional if statement. When someone wants to execute the loop more than five times, the if statement takes effect on the fifth iteration. The application displays a special message, then skips the rest of the loop. Execution begins with the next loop iteration. Notice that you must update SayIt or the application will end up in an endless loop. To see this function in action, type UsingContinue(8) and press Enter. You see the first four Howdy! messages, the special message, and then three ending Howdy! messages.
Ending processing using break
A loop can ordinarily execute a certain number of times and then stop without incident. However, when certain conditions are met, the loop may have to end early. For example, some people in your organization might be ramping up the Howdy! application into overdrive. To prevent this abuse, you want the loop to stop at five — friendly, but not too verbose. The break clause lets you stop the loop early.
Listing 10-5 shows how to use the break clause with a while loop, but you can use it in precisely the same way with the for loop. The examples in the “Making Decisions” section, earlier in the chapter, provide steps for creating functions. You can also find this function in the UsingBreak.m file supplied with the downloadable source code.
LISTING 10-5 Using the break Clause
function [ ] = UsingBreak( Times )
%UsingBreak: Demonstrates the while loop
% Tell the application how many times to say hello!
% Don't exceed five times or the application will cut you off!
if nargin < 1
Times = 3;
end
SayIt = 1;
while SayIt <= Times
disp('Howdy!')
SayIt = SayIt + 1;
if SayIt > 5
disp('Sorry, too many Howdies')
break;
end
end
end
The code executes precisely the same way that the SimpleWhile example works except that this version contains an additional if statement. When someone wants to execute the loop more than five times, the if statement takes effect. The application displays a message telling the user that the number of Howdies has become excessive and then calls break to end the loop. To see this example in action, type UsingBreak(10) and press Enter in the Command Window.
Ending processing using return
Another way to end a loop is to call return instead of break. The basic idea is similar. See the upcoming “Differentiating between break and return” sidebar for details on how the two clauses differ.
Listing 10-6 shows how to use the return clause with a while loop, but you can use it in precisely the same way with the for loop. The examples in the “Making Decisions” section, earlier in the chapter, provide steps for creating functions. You can also find this function in the UsingReturn.m file supplied with the downloadable source code.
LISTING 10-6 Using the return Clause
function [ Result ] = UsingBreak( Times )
%UsingBreak: Demonstrates the while loop
% Tell the application how many times to say hello!
% Don't exceed five times or the application will cut you off!
if nargin < 1
Times = 3;
end
Result = 'Success!';
SayIt = 1;
while SayIt <= Times
disp('Howdy!')
SayIt = SayIt + 1;
if SayIt > 5
disp('Sorry, too many Howdies')
Result = 'Oops!';
return;
end
end
end
Notice that this example returns a Result to the caller. The value of Result is initially set to 'Success!'. However, when the user gets greedy and asks for too many Howdies, the value changes to 'Oops!'. To test this example, begin by typing disp(UsingReturn()) and pressing Enter. You see the following output:
Howdy!
Howdy!
Howdy!
Success!
In this case, the application meets with success because the user isn’t greedy. Now type disp(UsingReturn(10)) and press Enter. This time the application complains by providing this output:
Howdy!
Howdy!
Howdy!
Howdy!
Howdy!
Sorry, too many Howdies
Oops!
DIFFERENTIATING BETWEEN BREAK AND RETURN
It may seem that break and return are almost precisely the same, but they really aren't. The UsingReturn example demonstrates one difference. You can provide a return value when using the return clause. In some cases, the ability to return a value is essential, and you must use return in place of break.
However, another difference isn’t quite so apparent. When you nest one loop inside another, the break clause ends only the inner loop, not the outer loop. As a result, the outer loop continues to run as before. In some cases, this is a desirable behavior, such as when you need to interrupt the current task but still want to execute the remaining tasks. Using return ends all the loops. In fact, the function containing the loops ends and control returns to the caller.
Determining which loop to use
You can understand the for and while loops better by comparing Listing 10-2 and Listing 10-3. A for loop provides the means to execute a set of tasks a precise number of times. You use the for loop when you know the number of times a task should execute in advance.
A while loop is based on a condition. You use it when you need to execute a series of tasks until the job is finished. (For example, when two functions are expected to converge on a particular value, you can use the while loop to detect the convergence and end the processing.) However, you don’t know when the task will end until such time as the conditions indicate that the job is done. Because while loops require extra code and additional monitoring by MATLAB, they tend to be slower, so you should use the for loop whenever possible to create a faster application.
Creating Menus
A menu is one way in which you can start to test the abilities you’ve gained in this chapter. Listing 10-7 shows a menu that you could use as a model for your own menu. Notice that this menu is a script. You could just as easily create a menu as a function. However, with all the emphasis on functions in this chapter, knowing that you can also use these techniques in scripts is important. You can also find this script in the MyMenu.m file supplied with the downloadable source code.
LISTING 10-7 A Simple Script Menu Example
EndIt = false;
while not(EndIt)
clc
disp('Choose a Fruit');
disp('1. Orange');
disp('2. Grape');
disp('3. Cherry');
disp('4. I''m Bored, Let''s Quit!');
Select = input('Choose an option: ', 's');
if isnan(str2double(Select))
disp('Provide numeric input, press Enter');
pause
continue;
end
if Select == '4'
disp('Sorry to see you go.');
EndIt = true;
else
switch Select
case '1'
disp('You chose an orange!');
case '2'
disp('You chose a grape!');
case '3'
disp('You chose a cherry!');
otherwise
disp('You''re confused, quitting!');
break;
end
pause(2)
end
end
The example begins by declaring a variable, EndIt, to end the while loop. A while loop is the perfect choice in this case because you don’t know how long the user will want to use the menu.
The example clears the Command Window and then displays the options. After the user enters a selection, the application checks to determine when it should end. If it should, it displays a goodbye message and sets EndIt to true.
This example is the first one to provide some sort of input checking. It uses str2double() to convert Select from a string into a double value. If the input isn’t numeric, str2double outputs the value NaN, or not a number. You can check for the NaN value using isnan(). When isnan() is true, the code tells the user to input only numeric values, and the user must press Enter to continue. The continue clause starts with the next iteration of the loop to give the user another chance.
When the user chooses some other numeric option, the code relies on a switch to provide a response. In this case, the response is a simple message, but your production application would perform some sort of task. When a user provides a useless response, the application detects it and ends. Notice the use of the break clause.
The pause(2) function is new. Because the Command Window is cleared after each iteration, the pause(2) function provides a way to display the response for two seconds. The user can also choose to press Enter to return to the menu early.