© Irfan Turk 2019
I. TurkPractical MATLABhttps://doi.org/10.1007/978-1-4842-5281-9_2

2. Fundamentals of MATLAB Language

Irfan Turk1 
(1)
Nilufer, Bursa, Turkey
 

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 %}.

To generate longer comments, the %{ symbol should be standing alone on a line. Similarly, the %} symbol used for closing the comment block should also be standing alone on the last line, as shown in Figure 2-1.
../images/483991_1_En_2_Chapter/483991_1_En_2_Fig1_HTML.jpg
Figure 2-1

An example of a comment block

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.

A flowchart is a graphical representation of the steps in writing the program. Simple shapes and diagrams (Table 2-1) are used to describe the algorithm of a computer program.
Table 2-1

Most Frequently Used Flowchart Symbols

../images/483991_1_En_2_Chapter/483991_1_En_2_Figa_HTML.gif

Used for initiating and finishing the program

../images/483991_1_En_2_Chapter/483991_1_En_2_Figb_HTML.gif

Used to indicate calculations, or assigning

../images/483991_1_En_2_Chapter/483991_1_En_2_Figc_HTML.gif

Used to indicate decision processes

../images/483991_1_En_2_Chapter/483991_1_En_2_Figd_HTML.gif

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.

Solution 2-1. For the pseudocode, the steps of the algorithm can be written as follows.
  1. 1.

    Enter the length of the square, called B.

     
  2. 2.

    Calculate the area of the square, Area= B^2.

     
  3. 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.

Solution 2-2. The flowchart of the algorithm can be drawn as shown in Figure 2-2.
../images/483991_1_En_2_Chapter/483991_1_En_2_Fig2_HTML.jpg
Figure 2-2

Flowchart of Example 2-2

Example2p2.m
%Example2p2
%this calculates the area and perimeter of a circle
Radius = input('Please enter the radius ');
AreA = pi*(Radius^2);
Per= 2*pi*Radius;
disp(['Area of the circle is= ',num2str(AreA)]);
fprintf('Perimeter of the circle is = % d ',Per);
Once the code is run, the following output is obtained.
>  Example2p2
Please enter the radius
10
Area of the circle is= 314.1593
Perimeter of the circle is =  6.283185e+01
>
In this solution, four important functions are used. The input command is used to externally enter the data. A numerical value is expected to be entered in the preceding code. The code is assigned to the variable named Radius. Both the disp and fprintf functions are used to display data. As seen from the code, though, their usages are different. The disp function displays the data between parentheses. After showing the string between single quotation marks, the numerical value of the variable AreA is converted to a string by using the num2str command, and then it is displayed with the disp function. When the fprintf function is used, again the data between quotation marks are shown. Here, though, the % symbol tells MATLAB that data will be printed. The letter coming after the % symbol is the specifier of the data. It tells MATLAB what kind of data will be printed. In this example, d is used to show a decimal number (Table 2-2). The cursor goes to the next line once ' ' is used. As a result, the value of the Per variable is printed as a decimal number after the script Perimeter of the circle is = .
Table 2-2

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.

Example2p3.m
%Example2p3
%This code shows three different pi
fprintf('pi : %f %.3f %15f ',pi,pi,pi)
Once the code is run, the following output is obtained.
> Example2p3
pi :
 3.141593
 3.142
     3.141593
>

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

In the case of using a single if statement , if the comparison statement after if is true, then the commands between if and end are executed. An example usage of the structure is given here:
if comparison
      statement
end

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.

Example2p4.m
%Example2p4
% This program rolls a pair of dice
Die=randi(6,1,2);
if Die(1)+Die(2)==10
    fprintf('You are LUCKY ')
end
fprintf('First # is %d Second # is % d ',...
Die(1),Die(2))

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.

After running the code, the following output will be obtained.
> Example2p4
First # is 1 Second # is  6
>

if-else Structure

If using a single if-else structure , it is possible to check more than one case in the program. An example usage of this structure is shown here.
if comparison
    statement
elseif comparison
    statement
else
  statement
end

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.

Example2p5.m
%Example2p5
% This program asks your age
Age = input('Please enter your age ');
if Age < 6
    fprintf('Maybe NO School ');
elseif Age <13
    fprintf('Middle School ');
elseif Age <18
    fprintf('High School ');
elseif Age <26
    fprintf('Maybe University ');
else % for other possibilities
    fprintf('Professional ')
end
Once the code is executed, the following output will be shown.
> Example2p5
Please enter your age
19
Maybe University
>

Relational Operators with if and if-else

Relational operators can be used with if and if-else structures as well. These operators are listed in Table 2-3.
Table 2-3

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.

Example 2-6. The age intervals that identify your status for getting a driver’s license are given in Table 2-4.
Table 2-4

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.

Example2p6.m
%Example2p6
%This program uses relational operators
Age=input('Please Enter Your Age ');
if Age<16
    fprintf('No license ');
elseif Age<18 && Age >=16
    fprintf('Can get a youth license   ');
elseif Age<70 && Age>=18
    fprintf('Can have a standard license ');
else % for the other possibilities
    fprintf('Should get a permitted license ');
end
If we run the code at the prompt, the output shown here results.
> Example2p6
Please Enter Your Age
41
Can have a standard license
>

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.

The usage of the switch-case ladder is shown here.
switch variable
    case option1
     In case of option1 do these
    case option2
     In case of option2 do these
    otherwise
    If none of the cases is applied, do this
  end

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.

Example2p7.m
%Example2p7
%This program has a switch-case illustration
Money=input('How much money you have? ');
switch Money
    case 20
        fprintf('You can eat Chicken ');
    case 30
        fprintf('You can eat Lobster ');
    case 40
        fprintf('You can eat Beef ');
    case 50
        fprintf('You can eat Fish ');
    otherwise % for other possibilities
        fprintf('No match with the menu ');
end
In this code, the number entered should match exactly with one of the numbers used with the case statement . Otherwise, the script written under the otherwise part is printed on the screen. Once the code is run, the following output is obtained.
> Example2p7
How much money you have?
40
You can eat Beef
>

Menu

The menu function is very useful in listing items. It can either be used with switch-case commands or with if-else commands, which make the appearance nicer. The usage of the menu function is represented as shown here.
Name   = menu('memutitle','option1','option2',...,'option')

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.

Example2p8.m
%Example2p8
%This code uses menu function
city=menu('Select a city from the menu',...
    'Houston','San Antonio','Dallas','Austin');
switch city
    case 1
        fprintf('$450 ');
    case 2
        fprintf('$550 ');
    case 3
        fprintf('$650 ');
    case 4
        fprintf('$750 ');
end
As shown in the first row, three consecutive periods (…) cut the line and extend the command to the next line. Once the program is executed, the interface shown in Figure 2-3 is obtained.
../images/483991_1_En_2_Chapter/483991_1_En_2_Fig3_HTML.jpg
Figure 2-3

Menu created for the venues

If the third option, Dallas, is selected, the following output will be obtained.
> Example2p8
$650
>

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

If the number of iterations is known, for loops are preferred to while loops. The configuration of this structure is easy to understand.
for starting_variable = Domain
        codes to be executed
end

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.

The flowchart of a for loop is displayed in Figure 2-4.
../images/483991_1_En_2_Chapter/483991_1_En_2_Fig4_HTML.jpg
Figure 2-4

Flowchart of a for loop

Example 2-9. Write a program that calculates the following series, which yields the value of ln2.
$$ {sum}_{i=1}^{infty}frac{{left(-1
ight)}^{i+1}}{i}=1-frac{1}{2}+frac{1}{3}-frac{1}{4}+dots dots = lnln (2)=0.693147.. $$

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.

Example2p9.m
%Example2p9
%This code calculates ln2
Total=0;
for i=1:1e+6 %1e+6=1000000
    Number=(-1)^(i+1)/i;
    Total = Total + Number;
end
fprintf('ln2= %d ',Total);
In the beginning, we define a sum equal to zero outside the loop . Then, each iteration is accumulated within that sum. The indexing variable i starts from 1, and continues up to 106. Once the program is executed at the prompt, the following output will be obtained.
> Example2p9
ln2= 6.931467e-01
>

As can be seen, the output is shown in scientific form. In other words, the output can be represented by 6,931467.10−1.

Example 2-10. Write a program that prints a triangle by using asterisks (*). The height is to be entered by the user. For instance, if the entered number is 3, then the code should print the following.
>> Height of the triangle? 3
Output:
*
**
***
Solution 2-10. We can write the following code.
%Example2p10
%This code draws a triangle
x=input('Height of the triangle? ');
for i=1:x
    for k=1:i
        fprintf('*');
    end
    fprintf(' ');
end
The output of this program is shown here.
> Example2p10
Height of the triangle?
5
*
**
***
****
*****
>

while Loop

In some cases, we might not know the number of iterations within the loop. In such cases, it is preferable to use the while loop . Its usage can be summarized in the following form.
while condition
        execute
end

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.

Example 2-11. Write a program that calculates the Euler number within the tolerance at least tol=0.001, where
$$ e={sum}_{i=1}^{infty}left(1+frac{1}{i!}
ight) $$

Solution 2-11. The following code can be used for this task.

WhileLo.m
%Example2p11
%This code calculates e
Total=1;
Eu=2.718281;
indeks=1;
tol=1; % arbitrarly defined away from Euler
while tol>1e-3
    Number=(1/(factorial(indeks)));
    Total = Total + Number;
    tol=abs(Eu- Total);
    indeks = indeks +1;
end
fprintf('Tolerance: %d e= %d ',tol,Total);
In this program , once the tolerance is not greater than 10−3, the program is terminated. The output becomes this.
> Example2p11
Tolerance: 2.254444e-04 e= 2.718056e+00
>

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.

Example2p12.m
%Example2p12
%A Guessing game with break command
Limit=100;%Can be changed
Picked_Number=randi(Limit,1);
Counter=1; %initializing counter
Gues=input('Enter your guess ');
while true
    if Gues==Picked_Number
        fprintf('Got it in your %d th try ',Counter);
        break;
    elseif Gues>Picked_Number
        Gues=input('Enter a SMALLER number ');
    elseif Gues<Picked_Number
        Gues=input('Enter a BIGGER number ');
    end
    Counter=Counter+1;
end

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.

Once we run the code, the following output will be shown.
> Example2p12
Enter your guess
50
Enter a SMALLER number
10
Enter a SMALLER number
5
Enter a SMALLER number
3
Enter a SMALLER number
1
Enter a BIGGER number
2
Got it in your 6 th try
>

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.

Example2p13.m
%Example2p13
%This code uses continue command
Counter = 3;
while Counter>0
    Number = input('Enter a number ');
    if Number<0
        fprintf('The number should be positive ');
        continue;
    end
    fprintf('Square root of %d is =%d ',...
        Number,sqrt(Number));
    Counter = Counter-1;
end
The following output will be obtained once this code is executed.
> Example2p13
Enter a number
-2
The number should be positive
Enter a number
3
Square root of 3 is =1.732051e+00
Enter a number
9
Square root of 9 is =3
Enter a number
4
Square root of 4 is =2
>

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

While running code, unexpected circumstances or errors might occur. To overcome this obstacle and take the necessary actions, the try-catch block is used. This block is composed of two parts. The first part is followed by try and the second part is followed by the catch statement.
try
      statement
catch
      statement
end

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.

Example2p14.m
%Example2p14
%This code uses try-catch block
try
    M1=10;
    M2=20;
    Multp = CallFunctionToMultiply(M1,M2);
    fprintf("Multiplication is %f ",Multp);
    disp("Everything was smooth")
catch
    warning('Something is wrong');
end
Obviously, the program will call the CallFunctionToMultiply(M1,M2) function for calculation. User-defined functions are examined in the next section. Here, though, because the function is not defined, the program will give the warning written in the warning function. The following output will be obtained once the code shown earlier is executed.
> Example2p14
Warning: Something is wrong
> In Example2p14 (line 10)
>

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.

In a user-defined function, the first line should start with the command function, generally followed by square brackets including one or more output variables, the function name, and parentheses including one or more input variables. The structure of the user-defined functions can be summarized as follows: In a user-defined function, the command function and the name to be assigned are sufficient to create a function. Functions generally end either with end statements placed as a final line, or with the definition of another subfunction. Although a user-defined function might occasionally work without the end statement, for better readability, using it as the last line of the code is recommended.
function [ output_variables ] = function_name( input_variables )
      code to be executed
end

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.

Beginning from the second half of 2016, with the R2016b version, another important feature has been incorporated into MATLAB that allows user-defined functions to be added at the end of the code within the same file. This new structure can be summarized as follows.
a piece of code
function function1
      code to be executed
end
function function2
      code to be executed
end

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.

Example2p15.m
function [ Result ] = Example2p15( Number )
%Example2p15
%This code accepts ant input
Checking_if_numeric = isnumeric (Number );
if Checking_if_numeric == 0 || nargin ~=1
    error('Just A NUMBER');
end
Result = Number^2;
end

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.

We will test both error and calculation cases from the command window. If we call the saved function from the command window, and enter a number, such as 5, we obtain the following output.
> My_udf(5)
ans =
    25
>
If we run the program for a second time, and pass a string such as G to the function, we obtain the following output.
> Example2p15(8,4)
Error using Example2p15
Too many input arguments.
>

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.

Example2p16.m
function [Perimeter,Area,Volume] = Example2p16(radius)
%Example2p16
%This function may print 3 outputs
Perimeter = 2*pi*radius;
Area = pi*(radius^2);
Volume = (4/3)*pi*(radius^3);
If we run the code from command window, we obtain the following result.
> [perimeter,area,volume]=Example2p16(10)
perimeter =
   62.8319
area =
  314.1593
volume =
   4.1888e+03
>

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.

Example2p17.m
%Example2p17
%This code uses local and global variables.
Numb1 = 61; %this is global variable
fprintf("Variable outside :%i ", Numb1)
MyFunction();%function is called
fprintf("Variable outside :%i ", Numb1)
function MyFunction
Numb1 = 55; %this is local variable
fprintf("Variable inside :%i ", Numb1)
end
Once the code is executed, the following output results.
> Example2p17
Variable outside :61
Variable inside :55
Variable outside :61
>

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.

Example2p18.m
function Example2p18(Radius,height)
%Example2p18
% This PRIMARY FUNCTION calculates
% the volume of a cylinder
radius_sq = R_square(Radius);
Result = pi*height*radius_sq;
fprintf('The volume is %f ',Result);
end
function [r_sq]=R_square(Radius)
r_sq= Radius^2; %Sub-function
end

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.

The second function used in the program is an example of a subfunction. Once the program is executed, the following output will be shown.
> Example2p18(4,10)
The volume is 502.654825
>

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.

Example2p19.m
function [Output] = Example2p19(x,y)
%This is Example2p19
%This function has an anonymous func.
Multip = @(x,y) x*y;
Output =Multip(x,y);
After running the code, the following output will be obtained.
> Example2p19(5,6)
ans =
    30
>

Interaction with the Computer

In this section, we discuss the interaction between the programmer and the computer, in other words, dialog boxes. There are numerous dialog boxes in MATLAB such as errordlg, warndlg, msgbox, questdlg, and so on, to be used within the codes. Some examples of these dialog boxes and their explanations are given in Table 2-5.
Table 2-5

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

To illustrate the usage of a question dialog box, we could write the following code at the prompt.
> Picking = questdlg('What kind of Fruit would you like?',...
'Fruit Selection','Apple','Orange','Banana','Orange')
>
Once we press Enter, the output shown in Figure 2-5 is obtained.
../images/483991_1_En_2_Chapter/483991_1_En_2_Fig5_HTML.jpg
Figure 2-5

Output of a question dialog box

The following syntax appears at the prompt.
> Picking = questdlg('What kind of Fruit would you like?',...
'Fruit Selection','Apple','Orange','Banana','Orange')
Picking =
    'Banana'
>
To illustrate the use of a list dialog box, the following code can be used.
> d= listdlg('PromptString','What kind of Fruit would you like?',...
                'SelectionMode','single', 'ListString',{'Strawberry',...
                'Banana','Orange','Apple','Cherry','Cranberry'},...
                'Name','Select A Fruit','ListSize',[210 100])
d =
     1
>
Here, because the first option is picked, as shown in Figure 2-6, 1 is assigned to d.
../images/483991_1_En_2_Chapter/483991_1_En_2_Fig6_HTML.jpg
Figure 2-6

Output of a list 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.

Example2p20.m
%Example2p20
% This example uses inputdlg box
prompt = {'fontsize{12} Enter your Name:',...
    'fontsize{12}Length', 'fontsize{12} Width'};
title = 'CALCULATING AREA';
Defining = {'Alex','3','2'};%Default values
NumLines=[1 50]; % dimensions
opts.Interpreter = 'tex';
options.Resize='on';
options.WindowStyle='normal';
Vals=inputdlg(prompt,title,NumLines,Defining,opts);
Name=num2str(Vals{1});%value converted to string
LS=str2double(Vals{2});%value converted to double
SS=str2double(Vals{3});%value converted to double
Area = LS * SS; %Calculation is done
fprintf(" Hello %s The Area is :%i ",Name,Area)

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.

Once the program is executed, the output shown in Figure 2-7 is the result.
../images/483991_1_En_2_Chapter/483991_1_En_2_Fig7_HTML.jpg
Figure 2-7

Output of Example 2-20

After clicking OK without making any changes to the default values, the following output is obtained.
> Example2p20
 Hello Alex
 The Area is :6
>

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.

$$ f(x)=Big{frac{x+1}{x^2},-1le xle 0 frac{3-x}{x^2},0le xle 1 0,kern0.5em left|x
ight|&gt;1 $$
  • 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.

$$ e={sum}_{i=1}^{infty}left(1+frac{1}{i!}
ight) $$
  • 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.176.225