In this chapter, you will learn the basic concepts of algorithms, M-files, selection structures, controlling mechanisms of the MATLAB language, and user-defined functions.
A computer program is basically a set of instructions that tells the computer what to do. In MATLAB, for larger programs, sometimes called scripts, using an editor is preferred to typing the whole code sequence at the prompt. The problems that we have dealt with so far have been easy to execute and accomplish. It was sufficient to use the prompt alone for solving the problems encountered up to this point. We could also use the MATLAB editor to solve these problems, though. However, for larger and more complex problems, it is recommended that you keep your code together and organized in an editor. For that reason, we use the editor to create our codes for the problems as much as we can for the rest of the book.
It is not difficult to write complex, unclear code. After a while, though, if you look back to your code for some reason, such as upgrading or editing, it might be difficult to understand what you meant. Therefore, one of the primary concerns when creating code is to write clear code that is easy to understand. To accomplish that, we could put our comments within the code as reminders after the % symbol. MATLAB ignores whatever comes after the % symbol. These comments can be placed either after a line of code, or as comment blocks, which are longer informative expressions between %{ and %}.
Another important rule for obtaining more organized codes is to use meaningful names for variables and structures. That helps users recall scripts easily later on. Some other useful tips related to writing better code is outside the scope of this book. For a basic understanding of the subject, though, we keep it simple here.
Algorithms
An algorithm is a computational procedure that shows all the steps involved in solving a problem. In general, an input (or a set of inputs) is (are) taken and an output (or some outputs) is (are) produced. When solving a problem, the problem is separated into parts to analyze and solve the constituent pieces separately. In this way, the problem can be analyzed in a more detailed manner. This method is often called a top-down approach. Sometimes, the pieces are combined to get information about the entire system, yielding more complex systems. The system can be constructed by analyzing and combining the pieces about which we have already gathered information. This method is called bottom-up processing.
In either method, the purpose of an algorithm is to define a solution to a problem in some way, such as writing the solution via simple expressions, or showing the solution using flowcharts.
Flowcharts and Pseudocode
Both pseudocode and flowcharts are used to construct an algorithm of a computer program. Pseudocode is generally composed of words and expressions, whereas flowcharts are represented by a set of simple shapes.
Pseudocode provides an informal means for describing the steps of the program to be written. It helps the programmer plan and develop the ultimate algorithm for the computer program.
Most Frequently Used Flowchart Symbols
| Used for initiating and finishing the program |
| Used to indicate calculations, or assigning |
| Used to indicate decision processes |
| Used to indicate input or output processes |
Example 2-1. Construct pseudocode and a flowchart for an algorithm that calculates the area of a square. The edge length of the square is to be externally entered by the user.
- 1.
Enter the length of the square, called B.
- 2.
Calculate the area of the square, Area= B^2.
- 3.
Display the result, Area.
Scripts and M-Files
After an algorithm is decided on for solving the problem, the code will be generated to accomplish the given task. Code can be written in the MATLAB editor and saved as a file called *.m, where * is the name you assign to your program. Thus, the codes written in MATLAB are called m-files and these codes are called scripts or programs.
Example 2-2. Construct the flowchart of an algorithm and generate the code that calculates the area and perimeter of a circle, where the radius is entered by the user.
Formatting Text with Conversion Functions
Specifier | Explanation |
---|---|
c | Displays a single character |
d | Displays in signed decimal notation format |
e | Displays in exponential notation format |
f | Displays in fixed-point notation format |
s | Displays character vector or string array |
When a conversion function, such as num2str, sprint, or fprintf is used, the user can shape the alignment or precision up to a certain digit. For an illustration, look at the following example.
Example 2-3. Write a program that shows π three different ways. In the first way, the code should display the value of π. In the second case, the code should show three numbers after the decimal. In the third case, the code should print the value of π in 15 digits by aligning π toward the right side.
Solution 2-3. The following code can be used to accomplish the given task.
In the preceding code, when the cursor comes to %f , the code prints the value of π and goes to the next line. When it comes to %.3f for execution, it prints the three numbers after the decimal point and then goes to the next line. Finally, when it comes to execute %15f , π is shown in 15 digits with the alignment toward the right side padded with spaces as needed. The cursor then goes to the next line.
Logical Functions and Selection Structures
In some situations, we might need to pick an option from among a set of possible candidates. This selection can be achieved by using if, switch, or menu commands in MATLAB. In this section, we discuss each case separately.
if and if-else Commands
There are some cases where it is sufficient to use a single if statement alone, whereas the if-else structure is used primarily in more complex cases.
Single if Structure
Example 2-4. Write code that rolls a pair of dice. If the sum of the two numbers on the top faces is 10, then the computer should print “You are LUCKY.” The computer also should print the numbers on the screen.
Solution 2-4. To accomplish this task, the following code, which is saved as Example2p4.m, can be used.
In this code, randi(6,1,2) creates a 1 × 2 matrix randomly where the highest number is 6. The elements are all positive integers in this function, unlike the rand command. The variable Die has two elements. If the sum of these elements is 10, then the message “You are LUCKY” is printed on the screen. In the seventh row of the code, three dots (…) are used to tell MATLAB that the coding will continue. Finally, the numbers are printed on the screen.
if-else Structure
Example 2-5. Write a program that asks your age. If the entered age is less than 6, MATLAB should print “Maybe NO School” on the screen. If the age is between 6 and 12, it should print “Middle School.” If the age is between 13 and 17, it should print “High School,” and if the age is between 18 and 25, it should print “Maybe University.” Otherwise, the program should display “Professional” on the screen.
Solution 2-5. The following code can be used to accomplish the given task.
Relational Operators with if and if-else
Relational Operators
Operator | Description | Example |
---|---|---|
> | Greater than | 3 > 2 |
>= | Greater than or equal to | 4 >= 3 |
< | Less than | 2 < 3 |
<= | Less than or equal to | 2 <= 3 |
== | Equal to | 4 == 4 |
~= | Not equal to | 2 ~= 3 |
For an illustration, let us look at the following example.
Ages for Getting a Driver’s License
Interval | License Condition | Comment |
---|---|---|
Age<16 | No license | No license |
16<=Age<18 | Youth license | Can get a youth license |
18<=Age<70 | Standard license | Can have a standard license |
70<Age | Permitted License | Should get a permitted license |
Write a computer program that requests your age and prints one of the comments given in Table 2-4 accordingly.
Solution 2-6. The following code can be used to accomplish the given task.
Switch-Case Commands
Switch-case commands are very similar to the if-else structure. Whatever is programmed using the if-else commands can be programmed using the switch-case structure as well. There are minor differences between switch-case and if-else structures. Reading the conditions in a switch-case type might be easier compared to the if-else type. However, the switch-case structure is less flexible than the if-else structure due mainly to its nature.
Example 2-7. Write a program that, for an amount of money such as $20, $30, $40, or $50 entered by the user, tells you what you can eat from a list including chicken, lobster, beef, and fish, respectively.
Solution 2-7. The following code can be used for the given task.
Menu
Example 2-8. Write a program that offers four different places to go for vacation using menu. Depending on your choice, the program should tell you how much the vacation costs. The venues include Houston, San Antonio, Dallas, and Austin, and the prices are $450, $550, $650, and $750, respectively.
Solution 2-8: The code generated for this problem is given here.
Programming Controls
Until a given condition is reached, loop control statements are used to execute a certain part of the code. These loops are sometimes called repetition structures, as well. Similar to most programming languages, MATLAB has for loop and while loop structures. Within these loops. break and continue statements can be used to check conditions depending on the cases. Another important control mechanism is to use a try-catch block to overcome unexpected situations in MATLAB.
for Loop
In the given configuration, in general, Domain has two or three numbers specified. If it has two numbers, for example, index=1:5, then the loop repeats itself five times with an increment of 1 for each index value from 1 to 5. Once the index value equals 6, the computer gets out of the loop and continues with the rest of the script. If Domain has three numbers specified, for example, index =1:3:10, then the loop repeats itself four times for the values of index =1, index =4, index =7, and index =10 with an increment of 3 for the index values from 1 to 10. After the value of 10, the program gets out of the loop and continues with the next line of the code. If all indexing operations are not yet complete, then the loop keeps repeating itself. Another important feature of indexing in MATLAB is that indexing starts with 1, and it cannot start with 0.
If a large number is entered as the final value for the index variable, the process of running the code inside the loop could take longer . Depending on your computer’s hardware specifications, this might cause your computer to freeze.
Solution 2-9. In programming, a loop cannot be repeated indefinitely in general. Otherwise, it keeps running and does not stop. Therefore, we need to assign a limit to the loop to calculate the series. The higher the limit is, the better the results we obtain. On the other hand, we are limited by another factor, which is the speed of the code. Hence, the code gets slower as the limit chosen is higher. The following code can be used to accomplish the given task.
As can be seen, the output is shown in scientific form. In other words, the output can be represented by 6,931467.10−1.
while Loop
In this structure, if the condition is true, the program stays in the while loop. Unlike the for loop, in the while loop, we need to add an extra mechanism to control the condition so that we can get out of the loop. In general, one of two options are preferred to get out of a while loop. In the first option, the loop is broken using the break command if a planned scenario is reached. In the second option, an increment of the indexing variable is defined inside the loop. This is the most significant difference between the for loop and the while loop.
The flowchart of the while loop is almost the same as the one for the for loop.
Solution 2-11. The following code can be used for this task.
break and continue
In some cases, a loop might need to be terminated once a condition is tested. In such cases, the break command is used, which terminates the closest loop and gets out of it.
Example 2-12. Write a program that plays a “Guess the Number” game. The user should guess the number between 1 and 100 where the number is picked randomly by the program. The user will then be guided by the computer to guess either a larger or a smaller number. Finally, the program should print the number that was guessed correctly.
Solution 2-12. The following code can be used.
In the code given, a true statement is written next to the while command. In MATLAB, true is a logical variable that always has a value of 1. By writing while true in the seventh row of the program, we want the program to keep running until the selected number is guessed by the user. If the guessed number is equal to the number that the computer picked, then the number of tries is printed and the loop is terminated by the break command.
The continue command is used to redirect the code. Unlike with the break command, the program continues to work without terminating the closest loop.
Example 2-13. Write a program that asks for the user to enter three positive numbers to calculate its square root. If the entered number is negative, it shows a message indicating that the number should be positive.
Solution 2-13. The following code can be used for this problem.
As shown in the output, if a negative number is entered, the Counter is not decreased, and the program keeps asking for a new number. After entering three numbers, the program stops.
try-catch Block
Whatever is written in the try statement is regarded as a regular code written in the editor or at the prompt. When an error occurs in this part, the rest of the code within the try part is terminated and MATLAB jumps to the catch part. This second part is where the user plans to write the alternatives or explanations in the case of getting an error in the first part.
Example 2-14. Write a program that tries to multiply two numbers. The program should call a function for the multiplication that is not defined. The code should give a warning if something goes wrong.
Solution 2-14. The following code can be used to accomplish the given task.
User-Defined Functions
Users are allowed to define functions for specific purposes. To define a function in MATLAB, the program must be created within an m-file. In general, user-defined functions are saved as a single m-file to be used for later purposes.
As mentioned earlier, the output variables should be between square brackets and the input variables should be enclosed within parentheses. The function name should be identical to the name of the saved file.
Creating Functions
When writing a complex program, you might need to create your own functions. Actually, none of the programming languages offers a complete built-in function library for all kinds of problems. Therefore, specific functions can be created for specific purposes to make the programmer’s job easier.
Some user-defined functions return a single value, whereas some others return multiple values. A function might not even return any value. In this chapter, we present such types of functions.
Example 2-15. Write a function that prints the square of the number entered by the user. The program should also check whether a number is passed to the function.
Solution 2-15. To create a function, first we need to satisfy the requirements by writing the necessary parts of a function in an editor. We can check the number of inputs by using the nargin function to make sure that a number is entered by the user. The following code can be used to do that.
The name of the function is the same as the name of the file, Example2p15. The function accepts only a single numerical value. This function has an output defined as Result, and an input defined as Number.
After the program is executed, a logical variable, Checking_if_numeric, gets either 0 or 1. If the number is numeric, then 1 is assigned to the logical variable Checking_if_numeric, 0 otherwise. In the fifth row of the code, the line checks if the variable is zero, meaning that if it is not a number, or the number of inputs is different from 1, then the computer prints the error message, which is placed within the error function. In MATLAB, the || symbol is a logical or operator.
In some cases, we might need to get more than one output from our function as shown in the following example.
Example 2-16. Write a program that calculates the perimeter, area, and volume for a radius entered by the user.
Solution 2-16. The number of outputs should be three. The program is given here.
As it is seen, there are three outputs specified. If the outputs are not specified, only the first output is displayed.
Local and Global Variables
The variables that are defined inside a function are called local variables. Local variables are valid only inside the function, meaning that they are not saved into the workspace. To make these variables available outside the function, we need to add global to the left of the variables to define them as global. If you define a function inside another function and use a variable in both functions, again, that variable should be defined as a global variable in both functions. However, many professional programmers recommend avoiding global variables. Instead, passing values to the functions is recommended.
Example 2-17. Write a program that shows the differences between using a global variable inside and outside a function.
Solution 2-17. The following code can be used to accomplish the given task.
As shown in the code, the global variable Numb1 is defined outside the function and printed as 61. Once it is called by the MyFunction function, then the same variable is defined as and printed as 55 as well. After exiting the function, its value stays as it was as 61.
Creating Subfunctions
It is possible to create a file that includes all user-defined functions. The first function is defined as the main or primary function. The rest of the functions can be called from the main function to execute the corresponding tasks. Other functions included in the primary function are called subfunctions. To avoid confusion, the name of the primary function and the name of the saved code should be identical.
Example 2-18. Write a function to calculate the volume of a cylinder using a subfunction. The radius and the height of the cylinder should be passed to the function by the user.
Solution 2-18. The code can be written as shown in the following m-file.
As shown, the output of the primary function is not defined. Instead, the result is printed on the screen by the body part of the primary function.
Anonymous Functions
Anonymous functions are the functions that are not stored in a separate file. These functions are part of a program associated with one or more variables in the file. Anonymous functions possess the function_handle data type in MATLAB.
These functions involve the @ symbol in their definitions. The Sqr function, given by Sqr = @(x) sqrt(x), is an example of an anonymous function. The @ symbol tells MATLAB that Sqr is a function.
Example 2-19. Write a function that takes an input composed of two numbers and calculates their product by using an anonymous function. The product of the numbers should be printed on the screen.
Solution 2-19. The following code can be used for this purpose.
Interaction with the Computer
Examples of Dialog Boxes in MATLAB
Function | Explanation |
---|---|
inputdlg | Creates an input dialog box |
errordlg | Creates an error dialog box |
warndlg | Creates a warning dialog box |
msgbox | Creates a message dialog box |
helpdlg | Creates a help dialog box |
waitbar | Opens or updates the wait bar dialog box |
questdlg | Creates a question dialog box |
listdlg | Creates a list-selection dialog box |
Example 2-20. Write a function to calculate the area of a rectangle. The length and width of the rectangle should be entered by using the input dialog box. The name of the user should be entered into the dialog box, as well.
Solution 2-20. The following code can be used to accomplish the given task.
The command prompt is a cell array of strings that involve one value for each input. As shown in the preceding code, the font size can be arranged using the fontsize{ } structure. The variable NumLines sets the dimension of the inputs. It can be either a scalar value or a matrix. In the preceding code, str2double converts a string to double. The command str2num can be used, as well.
Problems
2.1. Construct the code and flowchart of a program that takes two inputs as the length and width of a rectangle, and in turn, calculates the area of the rectangle.
2.2. Construct the flowchart and pseudocode of an algorithm in which, for an entered number greater than 18, the program will print, “Yes you can take a driver’s license,” and otherwise, “No driver’s license.”
2.3. Write a program that offers three places to go for a vacation using the menu function. Depending on your choice, the program should tell you how much your vacation will cost. The venues include San Antonio, Austin, and Dallas, and the prices are $500, $400, and $300, respectively.
2.4. Write a program that requests the user to pick one of the three colors “Blue,” “Red,” and “Green,” using the menu function. The program is required to print the user’s choice on the screen.
2.5. Plot the graph of the following piecewise function within the interval of -4≤x≤4.
2.6. Using the asterisk (*) symbol, write code that prints a rectangle on the screen. The width and the length of the rectangle should be entered as positive integers via the input function.
2.7. Write a program that calculates the Euler number within the tolerance of 0.0000001. The formula is given below to calculate the number.
2.8. The formula for finding the Fibonacci numbers is fn=fn-1 + fn-2, where f(0)=1 and f(1)=1. Write code to calculate f(80).
2.9. Write a function that accepts three inputs. If the number of inputs is not adequate, the program should give an error message.
2.10. Write a program that involves a function in it. The program should calculate the area of a rectangle. The length and width of the rectangle are to be entered after the program is executed. After providing the inputs, these values should be passed to the functions within the program. The function should calculate the area of the rectangle and print that value on the screen.
2.11. Write a program that shows a list of four items. The program should print the name of the selected item from the list on the screen.