0% found this document useful (0 votes)
27 views44 pages

Chapter 6 OCR

The document discusses various types of user-defined functions in MATLAB, including those that return one or multiple values, as well as functions that perform tasks without returning values. It outlines the structure of function definitions, the importance of capturing output values, and provides examples of function usage. Additionally, it emphasizes good programming practices, such as separating calculation and printing tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views44 pages

Chapter 6 OCR

The document discusses various types of user-defined functions in MATLAB, including those that return one or multiple values, as well as functions that perform tasks without returning values. It outlines the structure of function definitions, the importance of capturing output values, and provides examples of function usage. Additionally, it emphasizes good programming practices, such as separating calculation and printing tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

MATLAB Programs

CONTENTS
functions that return menu-driven program syntax errors ó.1 More Types of
more than one value variable scope run-time errors User- Defined
Functions ... 193
functions that do not base workspace logical errors
return any values local variable tracing 5.2 MATLAB
side effects main function breakpoints Program
call—by—value g lobal variable breakpoint alley
Organization 202
modular programs persistent variable function stubs ó.3 Application:
main program declaring variables live script M enu -D riven
primary function bug code cells M odular
Program ..... 207
subfunction debugging
Variable
Scope .::::.214
Chapter3 introduced scripts and user-defined functions. In that chapter, we saw B.5 Debugging
how to write scripts, which aresequences of statements that are stored in MATLAB Techniques. 219
code files and then executed. We also saw how to write user-defined functions, also
ó.ó Live Scripts,
stored in MATLAB code files that calculate and returna single value. In this chapter,
Code Cells, and
we will expand on these concepts and introduce other kinds of user-defined func-
Publishing
tions. We will showhow MATLAB programs consist ofcombinationsofscripts and
Code ........... 225
user-defined functions. The mechanisms forinteractions of variables in code files
and the Command Window will be explored. Techniques forfinding and fixing Summary .......... 228
mistakes in programs will be reviewed. Finally, the use of live scripts created by Common
the Live Editor(new asofR20 lGa), and usingcodecells in scripts will be introduced. Pitfalls .............. 228
Programming Style
Guidelines ........ 228
6.1 MORE TYPES OF USER-DEFINED FUNCTIONS
We have already seen how to writea user-defined function, stored ina code file,
that calculates and returns one value. This is just one type of function. It is also
possible fora function to return multiple values and it is possible fora function
to return nothing. We will categorize functions as follows: 193

MATLAB“. http://dx.doi.org/I 0.I 0t G/B978-0-12-804525-I .0000G-4


Ò 20a7 Elsevier Inc. AII rights reserved.
C HAPTER 6: NATLAB Programs

• Functions that calculate and return one value


• Functions that calculate and return more than one value
• Functions that just accomplisha task, such asprinting, without returning
any values
Thus, although many functions calculate and return values, some do not.
Instead, some functions just accomplisha task. Categorizing the functions as
above is somewhat arbitrary, but there are differences between these three types
of functions, including the format of the function headers and also the way in
which thefunctions are called. Regardless of what kind offunction it is, all func-
tions must be defined and all function definitions consist of the header and the
body. Also, the function must be called for it to be utilized. All functions are
stored in code files that have an extension of .m.
In general, any function in MATLAB consists of the following:
• The function header (the first line); this has:
the reserved word function
if the function returns values, the name(s) ofthe output argument(s),
followed by the assignment operator (=)
the name ofthefunction (important: this should be the same
asthenameofthefile in whichthis function is stored to avoid confusion)
the input arguments in parentheses, if there are any (separated by
commas if there is more than one).
• A comment that describes what thefunction does (this is printed if help
is used).
• The body ofthefunction, which includes all statements, including
putting values in all output arguments if there are any.
• end at the end of the function.

6.1.1 Functions That Return More Than One Va\ue


Functions that return one value have one output argument, as we saw previ-
ously. Functions that return more than one value must, instead, have more than
one output argument in the function header in square brackets. That means
that in the body ofthefunction, values must be put inall output arguments
listed in the function header. The general form ofa function definition fora
function that calculates and reiurns more than one rolue looks like this:
functionname.m
function [output arguments] = functionname(input arguments)
%Comment describing the function
%Formatoffunction call

Statementshere; thesemust includeputtingvalues in alloftheoutput


arguments listedin theheader

end
ó.
1 M o reTypes of U ser-
D ef
in e d F u n ctio n s

In the vector of output arguments, the output argument names areby conven-
tion separated by commas.
Choosing New, then Function brings up a template in the Editor that can then
be filled in:
function [ output_args] =untitled(input_args)
%UNTITLEDSummaryofthis functiongoeshere
% Detailedexplanationgoeshere

end
Ifthis is not desired, it may be easier to start with New Script.
For example, here isa function that calculates two values, both thearea and the
circumference ofa circle; this is stored ina file called areacirc.m:
areacirc.m
function [area, circum) = areacirc(rad)
%areacircreturnstheareaand
%thecircumferenceofacircle
% Format: areacirc(radius)

area=pi * rad .*rad;


circum=2 *pi* rad;
end

As this function is calculating two values, there are two output arguments in
the function header (area and circum), which areplaced in square brackets [].
Therefore, somewhere in thebody ofthefunction, values have to be stored
in both.
As the function is returning two values, it is important to capture and store these
values in separate variables when thefunction is called. In this case, the
first value returned, the area of the circle, is stored ina variablea and the second
value returned is stored ina variable c:
>> Éa, --areacírc 47
a =
50.2655

25.1327

Ifthis is not done, only thefirst value returned is retained—in this case, the area:
>> dz sp (a ser c::i cc: (4) )
5 0 .2 6 5 5

Note that in capturing the values, the order matters. In this example, the func-
tion first returns the area and then the circumference of the circle. The order in
which values are assigned to the output arguments within the function, how-
ever, does not matter.
CHAPTER 6: NATLAB Programs

ûUICK QUESTION!
What would happen ifa vector of radii was passed to the > (a, cj = areachxc (I.• 4)
function? a =
3.1416 12.5664 28.2743 50.2655
Answer: As the.* operator Is usedin the function to multiply
rad by itself,a vector can be passed tothe input argument rad. '
6.2832 12.5664 18.8496 25.1327
Therefore, the results will also be vectors, so the variables on
the left side ofthe assignment operator would become vectors
of areas and circumfe°ences.

ûUICK QUESTION!
What if you want only the second value that is returned?
Answer: Function outputs can be ignored usinp the tilde:
6.2832 12.5664 18.8496 25.1327

The help function shows thecomment listed under the function header:

Thisfunctioncalculatestheareaand
thecircumferenceofacircle
Format: areacirc(radius)
The areacirc function could be called from the Command Window asshown
here, or froma script. Here isa script that will prompt theuser for the radius
of just one circle, call the areacirc function to calculate and return the area and
circumference of the circle, and print the results:
calcareacirc.m
%This scriptprompts the user for the radius of a circle,
% callsa functiontocalculateandreturnboth thearea
% andthecircumference, andprintstheresults
%It ignores units anderror-checking for simplicity

radius = input('Pleaseenter theradiusof thecircle: ');


[area, circ] = areacirc(radius);
fprintf('For a circle with a radius of %.1f,\n', radius)
fprintf('the area is %.1f and the circumference is %.lf\n',...
area, circ)

>> ca2careaczrc
Pleaseenter theradiusofthecircle: 5.2
Foracirclewitharadiusof 5.2,
thearea is84.9andthecircumference is32.7
ó.1 M o re Type s o f U se r-D efin e d F u n ctio n s

PRACTICE 6.1
Writea function per/marea that calcu fates and returns the perimeter and area ofa rectang Ie. Pass
the length and width of the rectangleas in put arguments. For example, this function might be
cafled from the following script:

ca1careaperim.m

% Prompt the user for the lengthandwidthof arectangle,


% call a function to calculate and return theperimeter
% andarea, andprint the result
% For simplicity it ignores units anderror-checking
length= input('Pleaseenter the lengthof therectangle: );
width= input('Pleaseenter the widthof the rectangle: );
[perim, area] =perimarea(length, width);
fprintf('For a rectangle witha length of %.1f and a', length)
fprintf(' widthof %.lf,\nthe perimeteris %.lf, ', width, perim)
fprintf(' andthearea is %.if\n', area)

As another example, considera function that calculates and returns three out-
put arguments. The function will receive one input argument representinga
total number of seconds and returns the number of hours, minutes, and
remaining seconds that it represents. For example, 75 15 total seconds is2 h,
5 min, and 15s because 75 15 =3 G00x 2 + GOx 5 + 15.
The algorithm is as follows.
• Divide the total seconds by 3600, which is the number ofseconds in an
hour. For example, 75 15/3600 is 2.0875. The integer part is the
number ofhours (e.g., 2).
• The remainder of the total seconds divided by 3600 is the remaining
number ofseconds; it is useful to store this ina local variable.
• The number ofminutes is the remaining number ofseconds divided by
GO (again, the integer part).
• The number ofseconds is the remainder of the previous division.
breaktime.m
function [hours, minutes, secs) =breaktime(totseconds)
%breaktimebreaksatotalnumberof seconds into
%hours, minutes, and remaining seconds
%Format: breaktime(totalSeconds)

hours = floor(totseconds/3600);
remsecs = rem(totseconds, 3600);
minutes = floor(remsecs/60);
secs = rem(remsecs,60);
end
C HA PTE R 6 : NATLAB Programs

An example of calling this function is:

15

As before, it is important to store all values that the function returns by using
three separate variables.

6.1.2 Functions That Accomp\isha Task Without


Returning Va\ues
Many functions do not calculate values but rather accomplisha task, such as
printing formatted output. As these functions do not return any values, there
are no output arguments in the function header.
The general form ofa function definition fora suction that does noi reiurn ony
ralues looks like this:
functionname.m
function functionname(inputarguments)
% Commentdescribingthe function

Statementshere
end

Note what is missing inthe function header: there are no output arguments and
no assignment operator.
For example, the following function just prints the two arguments, numbers,
passed to it in a sentence format:
printem.m
functionprintem(a,b)
% printemprints twonumbers in a sentence format
% Format: printer(num1, num2)

fprintf('The first number is %.1f and the secondis %.lf\n',a,b)


end

As this function performs no calculations, there are no output arguments inthe


function header and no assignment operator (=). An example ofa call to the
printer function is:
>> pm:intem (3
.3, 2)
Thefi rst numberis 3 .3 and the secondis 2 .0
ó.
1 M o re Types of U ser-
D ef
in e d F u n ctio n s

Note that as the function does not returna value, it cannot be called from an
assignment statement. Any attempt to do this would result in an error, such as
the following:
>> x=printem(3, S) %Error!!
Error usingprintem
Toomanyoutputarguments.
We cantherefore think of the call toa function that does not return values asa
statement by itself, in that the function call cannot be imbedded in another
statement such as an assignment statement or an output statement.
The tasks that are accomplished by functions that do not return any values
(e.g., output from an fprintf statement ora plot) are sometimes referred to
as side effects. Some standards for commenting functions include putting the
side effects in the block comment.

PRACTICE 6.2
Writea function that receivesa vector as an in put argument and prints the individuaI elements
from the vector ina sentence format.

Element1 is 5.9
Element2 is33.0
Element3 is 11.0

6.1.3 Functions That Return Va\ues Versus Printing


A function that calculates and reiurns values (through the output arguments)
does not normally also print them; that is left to the calling script or function.
It isa good programming practice to separate these tasks.
Ifa function just printsa value, rather than returning it, the value cannot be
used later in other calculations. For example, here isa function that just prints
the circumference ofa circle:
calccircuml.m
function calccircuml(radius)
%calccircum1displaysthecircumferenceofacircle
% butdoesnotreturn thevalue
% Format: calccircum1(radius)

disp(2 *pi * radius)


end

Calling this function prints the circumference, but there is no way to store the
value so that it can be used in subsequent calculations:
>> ca2 cel rc uml (3.3 }
2 0 .7 3 4 5
100 C HAPTER 6: NATLAB Programs

Since no value is returned by the function, attempting to store the value ina
variable would be an error:
>> —— ca2ccircum2(3.37
Error using calccircuml
Toomanyoutputarguments.
Bycontrast, the following function calculates and returns the circumference, so that
itcan be stored and used inother calculations. For example, ifthe circle is the base of
a cylinder and we wish tocalculate the surface area of the cylinder, we would needto
multiply the result from thecalccircum2 function by the height of the cylinder.
ca1ccircum2.m
function circle circum= calccircum2(radius)
% calccircum2 calculates andreturns the
circumferenceofacircle
% Format: calccircum2(radius)

circle circum=2 * pi* radius;


end

>> c:1 scum Terence —— ca 2 cc::i xc:urn2 (3.3 )


circumference=
20.7345
>> he:ight =4 ;
>> suz/_azea = c::i re:umEerenOe * Ae1c/Ac
suz£_azea =
82 . 9380

One possible exception to this rule of not printing when returning is to havea
function returna value if possible but throw an error if not.

6.1.4 Passing Arguments to Functions


Inall function examples presented thus far, at least one argument was passed in
the function call to be the value(s) of the corresponding input argument(s) in
the function header. The call-by-ralue method is the term forthis method of
passing the values of the arguments to the input arguments in the functions.
In some cases, however, it is not necessary to pass any arguments to the
function. Consider, for example,a function that simply printsa random real
number with two decimal places:
printrand.m
functionprintrand()
% printrandprintsonerandomnumber
% Format: printrandorprintrand()

fprintf('The random# is %.2f\n',rand)


end
ó.
1 M o re Types of U ser-
D ef
in e d F u n ctio n s I

Here is an example of calling this function:


>>prïntrand()
The random# is 0 .94

As nothing is passed to the function, there are no arguments intheparentheses


in the function call and none inthefunction header, either. The parentheses are
not even needed ineither the function or the function call, either. The following
works aswell:
printrandnp.m
functionprintrandnp
% printrandnpprints one randomnumber
% Format: printrandnp orprintrandnp()

fprintf('The random# is %.2f\n',rand)


end

>>príntrandnp
Therandom# is 0.52
Infact, the function can be called with or without empty parentheses, whether
or not there are empty parentheses in the function header.
This was an example ofa function that did not receive any input arguments nor
did it return any output arguments; it simply accomplisheda task.
The following is another example ofa function that does not receive any input
arguments, but in this case, it does returna value. The function prompts the
user fora string and returns the value entered.
stringprompt.m
functionoutstr = stringprompt
% stringpromptpromptsfora stringand returns it
% Formatstringpromptor stringprompt()

disp('Whenprompted, entera stringofany length. ')


outstr = input('Enterthe stringhere: ', 's');
end

>> mystríng=stríngprompt
Whenprompted, enter a string of any length.
Enter the stringhere: Hi there
mystring=
Hi there

PRACTICE 6.3
Writea function that will prompt the user fora string of at least one character, loop to error-check
to make sure that the string has at feast one character and return the string.
106 CHAPTER 6: NATLAB Programs

ûUICK QUESTION!
It is important that the number ofarguments passed in the Answer: The fi°st proposed function call, (a], is valta. There
call toa function must be the same as thenumber ofinput are three arguments that are passed tothe three input argu -
arguments in the function header, even if that number Is zero. ments in the function header, the name ofthefunction is qq /,
Also. !fa function returns more than one value, it is important and there are two variables in the assignment statement to
to "capture" all values by having an equivalent number ofvari- store the two values returneo from thefunction. Function call
ables ina vector on the left side of an assignment statement. (b) is valid, although only the first value returned from the
Although it is not an error if there aren”t enough variables, function would be stored in answer; the second value would
some ofthevalues returned wi II be lost. The following ques- be lost. Function call lc] is invalid because the name ofthe
tion is posed to highlight this. function is given incorrectly. Function call (d] is invalid
because only two arguments are passed to the function, but
Given the following function header (note that this is just the
there are three input arguments in the function header.
function header, not the entire function definition]:

function [outa, outb] =qql(x, y, z)

Which ofthe following proposed calls to this function would


be valid?

(a) [varl, var2] =qql(a, b, c);


(b)answer- qql(3, y, q);
(c) [a,b) =myfun(x, y, z);
(d) louta, outb] =qql(x, z);

6.2 MATLAB PROGRAM ORGANIZATION


Typically,a MATLAB program consists ofa script that calls functions to do the
actual work.

6.2.1 Modu\ar Programs


A modular program isa program in which the solution is broken down into
modules, and each is implemented asa function. The script that calls these
functions is typically called the moin program.
To demonstrate the concept, we will use the very simple example of calculat-
ing the area ofa circle. In Section G.3a much longer example will be given. For
this example, there are three steps in the algorithm to calculate the area ofa
circle:
• Get the input (the radius)
• Calculate the area
• Display the results

Ina modular program, there would be one main script (or, possiblya function
instead) that calls three separate functions to accomplish these tasks:
6.2 MATLABP ro
g ram0 rg
a niz ation I

• A function to prompt theuser and read in the radius


• A function to calculate and return the area of the circle
• A function to display the results

As scripts and functions are all stored in code files that have an extension of .m,
there would therefore be four separate code files altogether for this program;
one script file and three function code files, as follows:
calcandprintarea.m
%This is the main script tocalculate the
% areaofacircle
%It calls3 functionstoaccomplishthis
radius = readradius;
area= calcarea(radius);
printarea(radius,area)

readradius.m
function radius =readradius
% readradiuspromptsthe userandreadstheradius
% Ignoreserror-checking fornow for simplicity
% Format: readradius or readradius()

disp('Whenprompted, pleaseenter theradius ininches. ')


radius = input('Enter theradius: );
end

ca1carea.m
functionarea= calcarea(rad)
% calcareareturnstheareaofa circle
% Format: calcarea(radius)

area=pi * rad .* rad;


end

printarea.m
functionprintarea(rad,area)
% printareaprintstheradiusandarea
% Format: printarea(radius, area)

fprintf('For acircle witha radius of %.2f inches,\n',rad)


fprintf('the area is %.2f inches squared.\n',area)
end

When theprogram is executed, the following steps will take place:

• the script calcandprintarea begins executing


• calcandprintarea calls the readradius function
readradius executes and returns the radius
204 CHAPTER 6: NATLAB Programs

• calcandprintarea resumes executing and calls the calcarea function, passing


the radius to it
calcarea executes and returns the area
• calcandprintarea resumes executing and calls the printarea function,
passing both the radius and the area to it
printarea executes and prints
• the script finishes executing
Running theprogram would be accomplished by typing the name ofthescript;
this would call the other functions:
>> ca2candprintarea
Whenprompted, pleaseentertheradiusininches.
Enter the radius: 5.3
Foracirclewith aradiusof 5.30 inches,
thearea is 88.25 inchessquared.
Note how thefunction calls and the function headers match up.Forexample:
readradius function:
function call: radius= readradius,
functionheader: functionradius= readradius
Inthereadradius function call, no arguments arepassed so there are no input
arguments in the function header. The function returns one output argument
so that is stored in one variable.
calcarea function:
function call: area= calcarea(radius),
functionheader: functionarea= calcarea(rad)
In thecalcarea function call, one argument is passed in parentheses so there is
one input argument in the function header. The function returns one output
argument so that is stored in one variable.
printarea function:
function call: printarea(radius,area)
functionheader: functionprintarea(rad,area)
Intheprintarea function call, there are two arguments passed, so there are two
input arguments inthe function header. The function does not return anything,
so the call to the function isa statement by itself; it is not in an assignment or
output statement.

PRACTICE 6.4
Modify the readradius function to error-check the user's input to make sure that the radius is valid.
The function should ensure that the radius isa positive number bylooping to print an error mes-
sage until the user entersa va did radius.
6.2 MATLABP ro
g ram0 rg
a niz ation I

6.2.2 Subfunctions
Thus far, every function has been stored ina separate code file. However, it is pos-
sible to have more than one function ina given file. For example, if one function
calls another, the first (calling) function would betheprimary function and the func-
tion that is called isa subfunction. These functions would both be stored in the same
code file, first the primary function and then thesubfunction. The name ofthecode
file would be thesame asthename oftheprimary function, to avoid confusion.
To demonstrate this,a program that is similar to the previous one, but calcu-
lates and prints the area ofa rectangle, is shown here. The script, or main pro-
gram, first callsa function that reads the length and width oftherectangle, and
then callsa function to print the results. This function callsa subfunction to
calculate the area.
rectarea.m
% Thisprogram calculates Sprints theareaof arectangle

% Call a fn toprompt the user &read the lengthandwidth


[length, width] = readlenwid;
% Call a fn to calculate andprint the area
printrectarea(length, width)

readlenwid.m
function [l,w] = readlenwid
% readlenwidreads &returns the lengthandwidth
% Format: readlenwid or readlenwid()

1 = input('Pleaseenter thelength: ');


w= input('Pleaseenter thewidth: );
end

printrectarea.m
functionprintrectarea(len, wid)
% printrectareaprints therectanglearea
% Format: printrectarea(length, width)

% Call a subfunction to calculate the area


area = calcrectarea(len,wid);
fprintf('For a rectangle witha length of %.2f\n',len)
fprintf('anda widthof %.2f, the area is %.2f\n',
wid, area);
end

functionarea= calcrectarea(len, wid)


% calcrectarea returns the rectangle area
% Format: calcrectarea(length, width)
area = len* wid;
end
20f, CHAPTER 6: NATLAB Programs

An example of running this program follows:


>> rectarea
Please enter the length:6
Please enter the width:3
For a rectangle with a length of 6.00
and a widthof 3.00, the areais 18.00
Note how thefunction calls and function headers match up. For example:
readlenuiid function:
function call: [length, width] = readlenwid,
functionheader: function [l,w] = readlenwid
Inthereadlenwid function call, no arguments arepassed so there are no input
arguments in the function header. The function returns two output arguments
so there isa vector with two variables on the left side of the assignment state-
ment inwhich thefunction is called.
printrectarea function:
function call: printrectarea(length, width)
functionheader: functionprintrectarea(len, wid)
In theprintre£tarea function call, there are two arguments passed, so there are
two input arguments inthefunction header. The function does not return any-
thing, so the call to the function isa statement by itself; it is not in an assign-
ment oroutput statement.
calcrectarea subfunction:
function call: area= calcrectarea(len,wid),
functionheader: function area= calcrectarea(len, wid)
In the calcrectarea function call, two arguments are passed in parentheses
so there are two input arguments in the function header. The function returns
one output argument so that is stored in one variable.
The help command canbeused with thescript rectarea, the function readlenwid,
and with the primary function, printrectarea. To view the first comment inthe
subfunction, as it is contained within the printrectarea.m file, the operator > is
used to specify both theprimary and subfunctions:
>>he2prectarea
Thisprogram calculates&printstheareaofarectangle

>> he2pprlntrectarea
printrectareaprints the rectangle area
Format: printrectarea(length, width)
>> he2pprIntrectarea>ca2crectarea
calcrectareareturns the rectanglearea
Format: calcrectarea(length, width)
6.3 Applicatio n: Menu - Driven Modular Prog ram 203

PRACTICE 6.5
Fora right triang Ie with sides a, b, and c, wherec is the hypotenuse andB is the ang Ie between
sidesa and c, the lengths of sidesa and 6 are given by:

a = c* cos(8)
b = c* sin(8)
Writea script righttri that callsa function to prompt theuser and read in values forthe hypotenuse
and the angle (in radiansl, and then calfsa function to calculate and return the lengths of sidesa
andb anda function to print out all values ina sentence format. For simplicity, ignore units. Here
is an example ofrunning the script, the output format should be exactly as shown here:

Enter the hypotenuse: 5


Enter the angle: .7854
Fora right triangle withhypotenuse 5.0
andan angle 0.79between side a &the hypotenuse,
side ais 3.54 and sideb is 3.54

Forextra practice, do this using two different program organizations:


• One script that calls three separate functions
• One script that calls two functions; the function that calculates the lengths of the sides will be
a subfunction to the function that prints

6.3 APPLICATION: MENU-DRIVEN MODULAR PROGRAM


Many longer, more involved programs that have interaction with the user are
menu-driren, which means that the program printsa menu ofchoices and then
continues to loop toprint the menu ofchoices until the user chooses to end the
program.A modular menu-driven program would typically havea function
that presents the menu andgets the user's choice, as well as functions to imple-
ment theaction for each choice. These functions may have subfunctions. Also,
the functions would error-check all user input.
As an example of sucha menu-driven program, we will writea program to
explore the constant e.
The constant e, called the natural exponential base, is used extensively in math-
ematics and engineering. There aremany diverse applications of this constant.
The value of the constante is approximately 2.7183... Raisinge to the power of
20/› CHAPTER 6: NATLAB Programs

x, or e‘, is so common that this is called the exponential function. In MATLAB,


aswe have seen, there isa function for this, exp.
One way to determine the value ofe is by findinga limit.
1
e = lim 1 + —

As the value ofn increases toward infinity, the result of this expression
approaches the value of e.
An approximation for the exponential function can be found using what is
calleda Maclaurin series:

e‘ m 1 + — + — + — + ...
1! 2! 3!

We will writea program to investigate the value ofe and the exponential
function. It will be menu-driven. The menu options will be:

• Print an explanation of e.
• Prompt theuser fora value ofn and then find an approximate value fore
using the expression (1+ 1/n)‘.
• Prompt theuser fora value forx. Print the value of exp(x) using the
built-in function. Find an approximate value for e‘ using the Maclaurin
series just given.
• Exit the program.

The algorithm for the script main program follows:

• Calla function eoption to display the menu andreturn the user's choice.
• Loop until the user chooses to exit the program. Ifthe user has not chosen
to exit, the action of the loop is to:
Depending on theuser's choice, do one of the following:
- Calla function explaine to print an explanation of e.
- Calla function limite that will prompt theuser forn and calculate an
approximate value fore
- Prompt theuser forx and calla function expfn that will print both an
approximate value for e‘ and the value of the built-in exp(x).
Note that because any value forx is acceptable, the program does
not need to error-check this value.
Call the function eoption to display the menu andreturn the user's
choice again.
6.3 Application: Menu - Driven Modular Prog ram 203

The algorithm for the eoption function follows:


• Display the four choices.
• Error-check by looping to display the menu until the user chooses one of
the four options.
• Return the integer value corresponding to the choice.

The algorithm for the explaine function is:


• Print an explanation of e, the exp function, and how to find approximate
values.

The algorithm for the limite function is:


• Calla subfunction ashforn to prompt theuser for an
integer ri.
• Calculate and print the approximate value ofe using n.

The algorithm for the subfunction ashforn is:


• Prompt theuser fora positive integer for n.
• Loop toprint an error message and reprompt until the user entersa
positive integer.
• Return the positive integer ri.

The algorithm for the expfn function is:


• Receive the value ofx as an input argument.
• Print the value of exp(x).
• Assign an arbitrary value for the number oftermsn (an alternative
method would be toprompt theuser for this).
• Calla subfunction appex to find an approximate value of exp(x) usinga
series withn terms.
• Print this approximate value.

The algorithm for the appex subfunction is:


• Receivex and n as input arguments.
• Initializea variable for the running sum oftheterms inthe series (to1 for
the first term) and fora running product that will be the factorials in the
denominators.
• Loop toadd then terms to the running sum.
• Return the resulting sum.
C HAPTER 6: NATLAB Programs

Theentire program consists of the following script file and four function code
files:
eapplication.m
%Thisscriptexploreseand theexponential function

%Calla function todisplay amenu andgetachoice


choice= eoption,

%Choice4 is toexittheprogram
while choice -=4
switchchoice
case1
%Explaine
explaine,
case2
%Approximateeusinga limit
limite,
case3
%Approximateexp(x) andcomparetoexp
x= input('Pleaseenteravalue forx: '),
expfn(x),
end
%Displaymenu againandgetuser'schoice
choice= eoption;
end

eoption.m
function choice= eoption
%eoptionprintsamenuofoptionsanderror-checks
% until theuserchoosesoneoftheoptions
%Format: eoptionoreoption()

printchoices
choice= input(' ');
while-any(choice == 1:4)
disp('Error-pleasechooseoneoftheoptions. ')
printchoices
choice= input(' ');
end
end

functionprintchoices
fprintf('Pleasechooseanoption:\n\n');
fprintf('1) Explanation\n')
fprintf('2) Limit\n')
fprintf('3) Exponential function\n')
fprintf('4) Exitprogram\n\n')
end
ó.
3 A p pli
catio n:M enu -Driven M o du la
r P rog ram

explaine.m
functionexplaine
% explaineexplains alittlebitaboute
% Format: explaineorexplaine()

fprintf('Theconstanteiscalled thenatural')
fprintf(' exponentialbase.\n')
fprintf('Itis usedextensivelyinmathematicsand')
fprintf(' engineering.\n')
fprintf('Thevalueoftheconstanteis 2.7183\n')
fprintf('Raising etothepowerofxisso common that')
fprintf(' this iscalledtheexponential function.\n')
fprintf('Anapproximation foreis foundusinga limit.\n')
fprintf('Anapproximation fortheexponential function')
fprintf(' canbe foundusing a series.\n')
end

limite.m
function limite
limitereturnsan approximateofeusing a limit
Format: limiteor limite()
% Callasubfunction topromptuserforn
n=askforn,
fprintf('An approximation ofewithn= %dis%.2f\n', ...
n, (1+ 1/n) ’n)
end
functionoutn=askforn
askfornpromptstheuser forn
Formataskforn or askforn()
% Iterror-checkstomakesurenisapositiveinteger

inputnum= input('Enterapositiveinteger forn: ');


num2 = int32(inputnum),
whilenum2 = inputnum// num2 <0
inputnum= input('Invalid! Enterapositiveinteger: '),
num2 = int32(inputnum);
end
outn= inputnum;
end
204 CHAPTER 6: NATLAB Programs

expfn.m
functionexpfn(x)
% expfn comparesthebuilt-in functionexp(x)
% andaseriesapproximationandprints
% Format expfn(x)

fprintf('Valueofbuilt-in exp(x) is%.2f\n',exp(x))

% nisarbitrarynumberof terms
n= 10,
fprintf('Approximateexp(x) is %.2f\n', appex(x,n)
end

functionoutval= appex(x,n)
% appexapproximatese tothexpowerusingtermsup to
% x to thenthpower
% Format appex(x,n)

% Initialize the running sumin theoutputargument


% outval to1 (for the first term)
outval= 1,

fori= 1:n
outval=outval + (xi)/factorial(i),
end
end

Running thescript will bring up the menu ofoptions.


> > en pp1:i cv t: on
P1 ease choose an option:

(1)Explanation
(2)Limit
(3)Exponential function
(4) Exitprogram
Then, what happens will depend on which option(s) the user chooses. Every
time the user chooses, the appropriate function will be called and then this
menu will appear again. This will continue until the user chooses4 for ’Exit
Program.' Examples will be given of running the script, with different
sequences of choices.
In the following example, the user

• Chose1 for’Explanation’
• Chose4 for’Exit Program'

> > eapp11 caL1 on


PIease choose an opL1 on:
6.3 Application: Menu - Driven Modular Prog ram 203

The cowsCanC e i s ca22 ed the mat ura2 exponenti a2 base.


Zci s used etceastvery in ma enemaCi as and en9ineeatrig .
The ve1 ue oE t.lie constant ei s 2 . 7183
thai sing eC o the power oE x :i s so common I:mat th:i s :i s cv 1 led the exponenCi a2

Artapproximati orifor ei s Eoundu s:ing a 1:i m:i t..


An approximati ori:to t.he exponenti a2 Eunct::i on can fie Eound us:ing a series.
Plecse choose an opt.:i on :

(1) Exprarabi on
(2)L:i m:i t:
(3) ExponenI:i a1 EuncI::i on
(4 ) Ex:iI program

Inthefollowing example, the user

• Chose2 for’Limit'
When prompted forn, entered two invalid values before finally
enteringa valid positive integer
• Chose4 for’Exit Program'

> > eapp2i cati or


Please choose on opt.:i on :

En her a postti vei nt eger Eor n: -4


Znva2id ' Int er a pos:i I::i ve in C ever: 5 .6
Znva2id ' Int er a pos:i I::i ve in C ever: 10
An approximaCi or oE e w:i th n —-1 o :i s 2 . S 9
Please choose as opiz:i on -
204 CHAPTER 6: NATLAB Programs

To seethedifference in the approximate value fore as n increases,


the user kept choosing 2 for ’Limit, and entering larger and larger
values each time in the following example (the menu is not shown for
simplicity):
> eapp1:i cv I:i on
Enterapositiveinteger forn:4
An approximationofewithn=4 is2.44
Enterapositiveinteger forn: 10
An approximationofewithn=10 is2.59
Enterapositiveinteger forn: 30
An approximationofewithn=30 is2.67
Enterapositiveinteger forn: 100
An approximationofewithn=100 is2.70
Inthefollowing example, the user

• Chose3 for’Exponential function'


When prompted, entered 4.6 forx
• Chose3 for’Exponential function' again
When prompted, entered —2.3 forx
• Chose4 for’Exit Program'

Again, for simplicity, the menu options and choices are not shown.
> eapp1:i cv I:i on
Pleaseenteravalue forx: 4.6
Valueofbuilt-inexp(x) is 99.48
Approximateexp(x) is98.71
Pleaseenteravalue forx: -2.3
Valueofbuilt-inexp(x) is 0.10
Approximateexp(x) is0.10

6.4 VARIABLE SCOPE


The scope of any variable is the workspace in which it is valid. The workspace
created in the Command Window is called the base workspace.
As we have seen before, ifa variable is defined in any function, it isa local
variable to that function, which means that it is only known andused within
that function. Local variables only exist while the function is executing; they
cease to exist when thefunction stops executing. For example, in the following
function that calculates the sum of the elements ina vector, there isa local loop
variable i.
ó.4 Variab leS cope

function runsum=mysum(vec)
% mysum returnsthe sumofavector
% Format: mysum(vector)

runsum= 0;
for i=1:length(vec)
runsum= runsum+vec(i);
end
end

Running this function does not add any variables to the base workspace, as
demonstrated in the following:
>> c2ear
>> rto
>> aíso(mysum((5 9 1
15
>> rto

Inaddition, variables that are defined in the Command Window cannot be


used ina function (unless passed as arguments to the function).
However, scripts (as opposed to functions) do interact with the variables that
are defined in the Command Window. Forexample, the previous function is
changed to bea script mysumscript.
mysumscript.m
% This script sums a vector
vec= 1:5;
runsum= 0;
fori=1:length(vec)
runsum= runsum+vec(i);
end
disp(runsum)

Thevariables defined in the script do become part of the base workspace:


>> c2ear

>> who
Yourvariablesare:
i runsum vec

Variables that are defined in the Command Window canbeused ina script, but
cannot be used ina function. For example, the vector vec could be defined in the
Command Window (instead of in the script), but then used in the script:
CHAPTER 6: NATLAB Programs

mysumscriptii.m
%This script sums avector from the CommandWindow

runsum= 0;
fori=1:length(vec)
runsum=runsum vec(i);
end
disp(runsum)

>> c2ear
>> ver =I : 7,
>> mo
Yourvariablesare:
vec

>> mysumscriptiz
28
>> mo
Yourvariablesare:
i runsum vec

Note Because variables created in scripts and in the Command Window both usethe
This however, is very poor base workspace, many programmers begin scripts witha clear command to
programming style. It is eliminate variables that may have already been created elsewhere (either in
much better to pass the the Command Window orinanother script).
vector vec toa function.
Instead ofa program consisting ofa script that calls other functions to do the
work, in some cases programmers will writea main function to call the other
functions. So, the program consists of all functions rather than one script
and the rest functions. The reason for this is again because both scripts and
the Command Window usethebase workspace. By using only functions in
a program, no variables are added to thebase workspace.
It is possible in MATLAB aswell in other languages, to have global variables that
can be shared by functions without passing them. Although there are some
cases in which using global variables is efficient, it is generally regarded as poor
programming style and therefore will not be explained further here.

6.4.1 Persistent Variab\es


Normally, whena function stops executing, the local variables from that function
are cleared. That means that every timea function is called, memory is allocated
and usedwhile thefunction is executing, but released when it ends. Withvariables
that are declared aspersistent variables, however, thevalue is not cleared so the next
time the function is called, the variable still exists and retains its former value.
ó.4 Variab le Scope

The following program demonstrates this. The script callsa function /uncI
which initializesa variable count to 0, increments it, and then prints the value.
Every time this function is called, the variable is created, initialized to 0,
changed to 1, and then cleared when thefunction exits. The script then calls
a function func2 which first declaresa persistent variable count. If the variable
has not yet been initialized, which will be the case the first time the function is
called, it is initialized to 0. Then, like the first function, the variable is incremen-
ted and the value is printed. With thesecond function however, the variable
remains with its value when thefunction exits, so the next time the function
is called, the variable is incremented again.
persistex.m
%This scriptdemonstratespersistentvariables

% The first functionhas avariable "count"


fprintf('This is whathappens witha "normal" variable:\n')
funcl
funcl

%Thesecond functionhasapersistent variable "count"


fprintf('\nThis is whathappens withapersistentvariable:\n')
func2
func2

funcl.m
function funcl
% funcl increments anormalvariable "count"
% Format funcl or funcl()

count = 0;
count = count+ 1;
fprintf('The valueofcount is %d\n',count)
end

func2.m
function func2
% func2 incrementsapersistentvariable "count"
% Format func2 orfunc2()

persistentcount%Declarethevariable

if isempty(count)
count = 0;
end
count = count+ 1;
fprintf('Thevalue of count is %d\n',count)
end
218 CHAPTER 6: NATLAB Programs

The line
persistentcount

declares the variable count which allocates space for it but does not initialize it.
The if statement then initializes it (the first time thefunction is called). In many
languages, variables always have to be declared before they can be used; in
MATLAB, this is true only forpersistent variables.
The functions can be called from thescript or from theCommand Window, as
shown. For example, the functions are called first from the script. With the
persistent variable, the value of count is incremented. Then, fiincl is called
from the Command Window andfiinc2 is also called from the Command
Window. As thevalue of the persistent variable had the value 2, this time
it is incremented to 3.
>>pers£stex
This is whathappens witha "normal" variable:
Thevalueof count is1
Thevalueof count is1
This is whathappens withapersistentvariable:
Thevalueof count is1
Thevalueof count is2
> > Eun ct
Thevalueofcount is1

> > Eunc2


Thevalueofcount is3

Ascanbeseen from this, every time the function funcl is called, whether from
persisted or from the Command Window, thevalue of1 is printed. However,
with func2 the variable count is incremented every time it is called. It is first
called in this example from persisted twice, so count is1 and then 2.Then, when
called from theCommand Window, it is incremented to3 (so it is counting
how many times the function is called).
The way to restarta persistent variable is to use the clear function. The
command
> > ctearE uncI:i one

will reinitialize all persistent variables (see help clear for more
options). However, as of Version 2015a, a better method has been
established which is to clear an individual function rather than all of
them, e.g.,
> > ct ear E un c2
ó.
5 D e buggin g Te ch n iq ue s

PRACTICE 6.6
The following function posnum prompts the user to entera positive number and loops to error-
check. It returns the positive number entered by the user. It ca Elsa subfunction in the loop to print
an error message. The subfunction hasa persistent variable to count the number oftimes an
error has occurred. Here is an example ofcafling the function:

>> enteredvalue=posnum
Enter apositivenumber: -S
Error# l ... Followinstructions!
Does -S.00look likeapositivenumber toyou?
Enter apositivenumber: -33
Error# 2... Followinstructions!
Does-33.00 look likea positive number toyou?
Enter apositivenumber:6
enteredvalue =
6

Fill in the subfunction befow to accomp tish this.


posnum.m

functionnum=posnum
% Prompt useranderror-checkuntilthe
% userentersapositivenumber
% Formatposnumorposnum()

num= input('Enterapositivenumber: );
whilenum<0
errorsubfn(num)
num= input('Enter apositivenumber: ');
end
end

function errorsubfn(num)
% Fill this in

end

Of course, the numbering ofthe error messages will continue if the function is executed again
without clearing it first.

6.5 DEBUGGING TECHNIDUES


Any error ina computer program is calleda bug. This term is thought to date
back to the 1940s, whena problem with an early computer was found to have
210 C HAPTER 6: NATLAB Programs

been caused bya moth inthecomputer's circuitry! The process of finding errors
ina program and correcting them, is still called debugging.
As we have seen, the checkcode function can be used to help find mistakes or
potential problems in script and function files.

6.5.1 Types of Errors


There areseveral different kinds of errors that can occur ina program, which fall
into the categories of syntax errors, runtime errors, and logical errors.
Syntax errors are mistakes in using the language. Examples of syntax errors are
missinga comma or a quotation mark, or misspellinga word. MATLAB itself
will flag syntax errors and give an error message. For example, the following
string is missing the end quote:
>> mystr = 'ñoware you,
mystr = 'howareyou,

Error: AMATLAB stringconstant isnot terminatedproperly.


Ifthis type of error is typed ina script or function using the Editor, the Editor
will flag it.
Another common mistake is to spella variable name incorrectly; MATLAB will
also catch this error. Newer versions of MATLAB will typically be able to correct
this for you, as in the following:
>> val ue =6 ,
>> newval ue = valu+ 3 ;
Andefined functi on or vari añ2e ' va2u '.

Dldyoumean:
>>newva2ue=va2ue+3;
Runtime orexecution-time errors are found whena script or function is execut-
ing. With most languages, an example ofa runtime error would be attempting
to divide by zero. However, in MATLAB, this will return the constant Inf.
Another example would be attempting to refer to an element in an array that
does not exist.
runtimeEx m
%This script shows anexecution-time error

vec = 3:5;

fori = 1:4
disp(vec(i))
end
ó.
5 D e buggin g Te ch n iq ue s

The previous script initializesa vector with three elements, but then attempts to
refer toa fourth. Running it prints the three elements in the vector, and then an
error message is generated when it attempts to refer to the fourth element. Note
that MATLAB gives an explanation of the error and gives the line number inthe
script in which theerror occurred.
>> ruxtzmeBx
3
4
5
Attempted toaccessvec(4), indexoutofboundsbecausenumel(vec)=3.

ErrorinruntimeEx (line6)
disp(vec(i))
Logical errors are more difficult to locate because they do not result in any error
message.A logical error isa mistake inreasoning by the programmer, but it is not
a mistake in the programming language. An example ofa logical error would be
dividing by 2.54 instead of multiplying to convert inches to centimeters. The
results printed or returned would be incorrect, but this might not be obvious.
All programs should be robust and should wherever possible anticipate poten-
tial errors, and guard against them. For example, whenever there is an input
intoa program, the program should error-check and make sure that the input
is in the correct range of values. Also, before dividing, any denominator should
be checked to make sure that it is not zero.
Despite the best precautions, there are bound tobe errors in programs.

6.5.2 Tracing
Many times, whena program has loops and/or selection statements and is not
running properly, it is useful in the debugging process to know exactly which
statements have been executed. For example, the following isa function that
attempts to display “In middle of range” if the argument passed to it is in
the range from3 to G, and “Out of range” otherwise.
testifelse.m
function testifelse(x)
%testifelsewilltestthedebugger
%Format: testifelse(Number)

if3 Sxe 6
disp('Inmiddleof range')
else
disp('Out of range')
end
end
215 CHAPTER 6: NATLAB Programs

However, it seems to print “In middle of range” for all values of x:


>> testife1se{47
Inmiddleofrange

>> testifelse 77
Inmiddleofrange
>> testife1se{-27
Inmiddleofrange

Onewayoffollowing the flow of the function or tracing it, is to use the echo
function. The echo function, which isa toggle, will display every statement as it
is executed as well as results from thecode. For scripts, just echo can be typed,
but for functions, the name ofthefunction must be specified. For example, the
general form is
echo functionnameon/off

Forthetestifelse function, it can be called as:


> > echoI esI:i Eel se on
>> testife1se{-27
%Thisfunctionwill testthedebugger
if3 <x<6
disp('Inmiddleofrange')
Inmiddleofrange
end

We canseefrom this result that the action of the if clause was executed.

6.5.3 Editor/Debugger
MATLAB hasmany useful functions for debugging, and debugging can also be
done through its Editor, which is more properly called the Editor/Debugger.
Typing help debug attheprompt intheCommand Window will show some of
the debugging functions. Also, in the Help Documentation, typing
“debugging” in the Search Documentation will display basic information
about the debugging processes.
It can be seen intheprevious example that the action of the ifclause was executed
and itprinted “In middle ofrange,” but justfromthatitcannotbe determined why
this happened. There areseveral waystosetbreaitpoints ina file (script or function)
so that the variables or expressions can be examined. These can be done from the
Editor/Debugger or commands canbe typed from theCommand Window. For
example, the following dbstop command will seta breakpoint in the sixth line
of this function (which is the action of the ifclause), which allows the values of
variables and/or expressions to be examined atthat point in the execution. The
function dbcont can be used to continue the execution and dbquit can be used
to quit the debug mode. Note that the prompt becomes Km > indebug mode.
ó.
5 D e buggin g Te ch n iq ue s

>> dbstop testife2se6


>> testife2se -27
5 disp('Inmiddleofrange')
K>>x

-2
K>> 3<x
ans=
0

K>> 3<x<6
ans=

K>>dbcont
Inmiddleofrange
end

By typing the expressions3 < x and then3 <x < G, we can determine that the
expression3 <x will return either0 or 1. Both0 and1 areless than 6, so the
expression will always be true regardless of the value of x! Once inthedebug
mode, instead of using dbcont tocontinue the execution, dbstep can be used to
step through the rest of the code one line ata time.
Breakpoints can also be setand cleared through the Editor. Whena file is open in
theEditor, in between theline numbers on theleft and the lines of code isa thin
gray strip which is the breakpoint alley. In this, there are underscore marks next to
the executable lines of code (asopposed tocomments, forexample). Clicking the
mouse inthealley next toa line will createa breakpoint at that line (and then
clicking on the red dot that indicatesa breakpoint will clear it).

PRACTICE 6.7
The following script is bad code in several ways. Use checkcode first to check it for potential prob-
lems and then use the techniques described in this section to set breakpoints and check values of
variables.

debugthis.m

fori = 1:5
i = 3;
disp(i)
end

forj =2 :4
vec (j) =j
end
C HAPTER 6: NATLAB Programs

6.5.4 Function Stubs


Another common debugging technique that is used when there isa script main
program that calls many functions is to use function stubs.A function stub isa
place holder, used so that the script will work even though that particular func-
tion hasn't been written yet. For example,a programmer might start witha
script main program which consists of calls to three functions that accomplish
all of the tasks.
mainscript.m
%Thisprogramgets values forx andy, and
% calculatesandprintsz

[x,y] =getvals;
z = calcz(x,y);
printall(x,y,z)

Thethree functions have notyetbeen written however, so function stubs are put
inplace so thatthe script can be executed and tested. The function stubs consist of
the proper function headers, followed bya simulation of what thefunction will
eventually do. For example, the first two functions put arbitrary values in forthe
output arguments and the last function prints.
getvals.m
function [x,y) =getvals
x = 33;

end

calcz.m
function z= calcz(x,y)
Z = X + /,
end

printall.m
functionprintall(x,y,z)
disp(x)
disp(y)
disp(z)
end

Then, the functions can be written and debugged one ata time. It is much easier
to writea working program using this method than to attempt to write every-
thing atonce—then, when errors occur, it is not always easy to determine where
theproblem is!
ó.ó L ive S c ri pt s, C o d e C e lls, a nd P u b lis hin g C o d e

6.6 LIVE SCRIPTS, CODE CELLS, AND PUBLISHING CODE


An entirely new type of script has been introduced in MATLAB asofVersion
2016a. The script is calleda lire script and is created using the Live fiditor.
A live script is much more dynamic thana simple script; it can embed equa-
tions, images, and hyperlinks in addition to formatted text. Instead of having
graphs in separate windows, thegraphics are shown next to the code that cre-
ated them. It is also possible to put the graphs inline, under the code.
The scripts that we have seen so farhave been simple scripts, stored in files that
have an extension of .m. Live scripts are instead stored using the .mlx file
format.
An example ofa live script is shown inFig. G. 1. In this live script named "sintest.
mlx," there is text, followed by an equation, then code, more text, another equa-
tion, and more code. All of these are in separate sections. The sections are cre-
ated by clicking on "code," "text," "equation" and so forth from the "Insert"
section, with "section break" in between each type of section. All output,
including error messages if there are any, are shown totheright of the code.
In this case, the graphs produced by the code sections are shown totheright
of the code. Clicking on the icon above the graphs will move them inline.
There areseveral ways tocreatea live script. The simplest is to click on New, then
Live Script.A simple script can also be transformed intoa live script by choosing
Save As and then Live Script. Right clicking on a set of commands from theCom-
mand History window also pops up an option to save asa Live Script.

LJve Editor - /Users/sa/Desktop/Books/MATLAB Book4 E7’4EM Files/síntesi.mlx

” in i es =-_ m qua ion _

new open save “ *””’°" ’='° ^” ’°^" code Text sectton "’""" ’>’'"" Run
Aii eun

Let's createa vector x, and then show thedifference between seyeral tunc1ions of x. First,

FIGURE 6.1
TheLive Editor.
C HA PT E R 6 : NATLAB Programs

new open save C°""°re " '° ‘ '" co de Texr section “ "’”"" "" ”“' bun
Aii run
• • • @ Print Break Image Section ••

Untitled. mlx “ , •f• ,

FIGURE 6.2
"Run current section" from Live Editor.

All of the code from thelive script can be executed by choosing the Run Allbut-
ton. Alternatively, individual sections can be executed by clicking on the bar to
the left of the section as seen in Fig. G.2.
Oncea live script has been completed, it can be shared with others as an.mlx file,
or it can be converted toa PDF or HTML format. To do this, click on the down
arrow under "Save," and then either "Export to PDF" or"Export to HTML."
Live scripts can also be converted to code files with the .m extension by choos-
ing Save As and then choosing MATLAB Code file from thedrop down menu
fortheFormat.
Using thetype command ona live script will show just the code sections. The
entire contents of the .mlx file can be seen from theLive Editor.
>> typeszntest.m2x

x = -pi:0.01:pi;
y=x.’2.*sin(x),
plot(x,y, 'r*')
y=sin(x);
plot(x,y, 'bo')

PRACTICE 6.8
If you have R2016a or later, try creatinga five script with text, equ ations, and code top roduce at
least one p lot.

6.6.1 Code Ce\\s


With simple code file scripts, one can break the code into sections called code
cells. With code cells, you can run one cell ata time and you can also publish the
code in an HTML format with plots embedded and with formatted equations.
ó.ó L iveS c ri pt s, C o d e C e lls, a nd P u b lis hin g C o d e

To break code into cells, create comment lines that begin with two % symbols;
these become thecell titles. For example,a script from Chapter3 that plots sin
and cos has been modified to have two cells: one that creates vectors for
sin(x) and cos(x) and plots them; anda second that addsa legend, title, and
axis labels to the plot.
sinncosCells.m
%Thisscriptplots sin(x) andcos(x) in the sameFigure
%Window forvalues ofx ranging from0 to 2pi

%%Create vectorsandplot
clf
x = 0: 2*pi/40: 2*pi;
y=sin(x);
plot(x,y, 'ro')
holdon

plot(x,y, 'b ')

%%Add legends, axis labels, andtitle


legend('sin', 'cos')
xlabel('x')
ylabel('sin(x) or cos(x) ')
title('sin andcos on onegraph')

When viewing this script in the Editor, the individual cells can be chosen by
clicking the mouse anywhere within the cell. This will highlight the cell with
a background color. Then from the Editor tab, you can choose "Run
Section" to run just that one code cell and remain within that cell, or
you can choose "Run and Advance" to run that code cell and then advance
to the next.
By choosing the "Publish" tab and then "Publish," the code is published by
default in HTML document. For the plotl ptCells script, this createsa docu-
ment inwhich there isa table of contents (consisting of the two cell titles),
the first code block which plots, followed by the actual plot, and then the
second code block that annotates the Figure Window, followed by the mod-
ified plot.

■ Exp\ore Other lnteresting Features


From theCommand Window, type help debug tofind out more about the
debugging and help dbstop inparticular to find out more options forstop-
ping code. Breakpoints can be setat specified locations ina file, only when
certain condition(s) apply, and when errors occur.
Investigate the dbstatus function.
218 CHAPTER 6: NATLAB Programs

Explore the use of the functions mlock and munlock toblock functions
from being cleared using clear.
It is also possible to create code cells in functions. Investigate this. ■

SUMMARY
COMMON PITFALLS
• Not matching up arguments ina function call with the input arguments
ina function header.
• Not having enough variables in an assignment statement to store all of
the values returned bya function through the output arguments.
• Attempting to calla function that does not returna value from an
assignment statement, or from an output statement.
• Not using the same name forthefunction and the file in which it
is stored.
• Not thoroughly testing functions for all possible inputs and outputs.
• Forgetting that persistent variables are updated every time thefunction in
which they are declared is called—whether froma script or from the
Command Window.

PROGRAMMING STYLE GUIDELINES


• Ifa function is calculating one or more values, return these value(s) from
thefunction by assigning them tooutput variable(s).
• Give the function and the file in which it is stored the same name.
• Function headers and function calls must correspond. The number of
arguments passed toa function must be thesame asthenumber ofinput
arguments in the function header. If the function returns values, the
number ofvariables in the left side of an assignment statement should
match thenumber ofoutput arguments returned by the function.
• If arguments arepassed toa function in the function call, do not replace
these values by using input in the function itself.
• Functions thatcalculate and returnvalue(s) will not normallyalso printthem.
• Functions should not normally be longer than one page in length.
• Do not declare variables in the Command Window andthen use them in
a script, or vice versa.
• Pass all values to be used in functions to input arguments in the
functions.
• When writing large programs with many functions, start with the main
program script and use function stubs, filling in one function ata time
while debugging.
Programmi ng StyleG u ideli nes

global persistent

NATLAB Functlons añd !¢omr/iaotIs


echo dbqut
dbstop dbstep
dbcont

> path for subfunction %% code cell title

Exercises
1 Given the following function header:
function [x,y] = calcem(a, b, c)

Which ofthe following function calls would be valid—and why?


[num, val] = calcem(4, 11, 2)
result = calcem(3, 5, 7)

2 Writea function that will receive as an in put argumenta number ofkilometers


(KI. The function will convert the kilometers to miles and to US nautical
miles, and return both results. The conversions are:1 K 0.621 miles and1 US
nautical mile 1.852 K.
Writea function “splitem” that will receive one vector of numbers as an in put
argument, and will return two vectors: one with the positive (> 01 numbers
from theoriginal vector, and the second, the negative numbers from theoriginal
vector. Use vectorized code (no loopslin your function.
Writea function to calculate the volume and surface area ofa hollow cylinder. It
receives as in put arguments theradius ofthe cylinder base and the height ofthe
cylinder. The volume is given by ar2ñ, and the surface area is 2xrh.
Satellite navigation systems have become ubiquitous. Navigation systems based in
space such as the 6lobaI Positioning System IGPS) can send data to handheld
personal devices. The coordinate systems that are used to represent locations
present this data in several formats.
The geographic coordinate system is used torepresent any location on Earth as
a combination of latitude and longitude values. These values are ang les that
can be written in the decimal degrees (DD] form or the degrees, minutes,
210 CHAPTER 6: NATLAB Programs

and seconds (DMS] form just like time. For example, 2¢.5° is equivalent to 2¢°
30’0". Writea script that will prompt the user foran angle in DD form and
will print in sentence format the same angle in DMS form. The script should
error-check forinvalid user in put. The angle conversion is to be done by calling
a separate function from the script.
6 Given the following function header:
function doit(a, b)

Which ofthe following function calls would be valid—and why?

fprintf('Theresult is%.1f\n', doit(4,11))

doit(S, 2, 11.11)

x= 11,
y= 3.3,
doit(x,y)

Writea function that prints the area and circumference ofa circle fora
given radius. Only the radius is passed to the function. The function
does not return any values. The area is given by x and the circumference
is 2ar.
8 Writea function that will receive an integern and a character as input argu-
ments and will print the charactern times.
9 Writea function that receivesa matrix as an in put argument and printsa
random row from the matrix.
10. Writea function that receivesa count as an input argument and prints the value
of the count ina sentence that would read ‘It happened1 time." if the value of the
count is 1. or ‘It happened xx times.“ if the value of count (xx] is greater than 1.
11. Writea function that receives anx vector,a minimum value, and a
maximum value. and plots sinlx) from the specified minimum tothespecified
maximum.
12. Writea function that prompts the user fora value of an integern and returns
the value of n. No input arguments are passed to this function. Error-check
to make sure that an integer is entered.
13. Writea script that will:
Calla function to prompt the user foran angle in degrees
Calla function to calculate and return the angle in radians. (Note: x
radians= 180°I
Calla function to print the result
Write all of the functions, also. Note that the solution to this problem involves
four code files: one which acts asa main program (the script], and three for
the functions.
1L. Modify the program in Exercise 13 so that the function to calculate the angle isa
subfunction to the function that prints.
Prog rammi ng StyleG u i del i nes 219

15. In 3D space, the Cartesian coordinates (x,y,z] can be converted to spherical


coordinates (radius r, inclination 8, azimuth $l by the following equations:

r= 2 + 2+ 2, 8 —— cos"' —), ‹f› —— han"'( )

A program is being written to read in Cartesian coordinates, convert to


spherical. and print the results. So far,a script pracscripl has been written that
callsa function getcarlesian to read in the Cartesian coordinates anda function
printspherical that prints the spherical coordinates. Assume that the
getcartesian function exists and reads the Cartesian coordinates froma file. The
function printspherical callsa subfunction convert2spher that converts from
Cartesian to spherical coordinates. You are to write the printspherical function.
Here is an example:
>>pracscript
Theradius isS.46
Theinclinationangleis1.16
The azimuth angle is 1.07
pracscript.m

[x,y,z] =getcartesian(),
printspherical(x,y,z)

getcartesian.m

function [x,y,z] =getcartesian()


%Assume thisgetsx,y,z froma file
end

1 ó. The lump sumS tobe paid when interest ona loan is compounded annually is
given by S= P(1+/]" whereP is the principal invested,i is the interest rate, and n
is the number ofyears. Writea program that will plot the amountS as it
increases through the years from1 to n. The main script will calla function to
prompt theuser forthe number ofyears (and error-check to make sure that the
u ser entersa positive integer]. The script will th en calla function that will plotS
for years1 through n. It will use 0.05 for the interest rate and $10,000 for P.
17. Writea program towritea length conversion chart toa file. It will print lengths
in feet from1 to an integer specified by theu ser, in one column and thecor-
responding length in meters (1 foot= 0.30¢8 ml ina second column. The main
script will call one function that prompts theu ser forthe maximum length in
feet: this function must error-check to make sure that the user entersa valid
positive integer. The script then callsa function to write the lengths toa file.
18. The script circscript loopsn times toprompt theuser forthe circumference ofa
circle (wheren isa random integer]. Error-checking is ignored to focus on
functions in this program. For each, it calls one function to calculate the radius
and area of that circle, and then calls another function to print the se values.
The formulas are r= c/(2xI and a = x/ wherer is the radius,c is the circum-
ference, and a is the area. Write the two functions.
CHAPTER 6: NATLAB Programs

circscript.m

n= randi(4);
fori = 1:n
circ= input('Enter thecircumferenceofthecircle: );
[rad, area) = radarea(circ);
dispra(rad,area)
end

19 The distance between any two points (x/,y/] and (x2,y2)iS given by:

The area ofa triang ie is:

area s ) b) c)

where a, b, and c are the Ie ngths of the sides of the triang ie, and s is equal
to half the sum of the lengths of the three sides of the triang ie. Writea
script that will prompt the user to enter the coordinates of three points that
determine a triang Ie (e.g., the x and y coordinates of each pointl. The
script will then calculate and pri nt the area of the triang ie. It will call
one function to calculate the area of the triang ie. This function will calla
subfunction that calculates the length of the side formed by any two points
(the distance between them].
20 Writea program towritea temperature conversion chart toa file. The main
script will:
calla function that explains what the program will do
calla function to prompt the user forthe minimum and maximum tem-
peratures in degrees Fahrenheit and return both values. This function
checks to make sure that the minimum is less than the maximum andcalls
a subfunction to swap thevalues if not.
calla function to write temperatures toa file: the temperature in degrees
F from the minimum tothemaximum in one column and the
corresponding temperature in degreesC in another colum n. The conversion
isC (F— 321 x 5/9.
2 1 Modify the function func2 from Section 6.¢.1 that hasa persistent variable count.
Instead of having the function print the value of count, the value should be
returned.
22 Writea function per2 that receives one number as an in put argument. The
function hasa persistent variable that sums thevalues passed to it. Here are
the first two times the function is called:
> > p ec2 (4}
ans =
4
Programming StyleG u ideli nes

> > per2( 6)


ans =
10
23 What would be the output from the following program? Think about it, write
down your answer and then type it in to verify.
testscope.m

answer = 5;
fprintf('Answer is %d\n',answer)
pracfn
pracfn
fprintf('Answer is %d\n',answer)
printstuff
fprintf('Answer is %d\n',answer)

pracfn.m

functionpracfn
persistentcount
if isempty(count)
count= 0;
end
count = count+ 1;
fprintf('This functionhas been called %dtimes.\n',count)
end

printstuff.m

functionprintstuff
answer = 33;
fprintf('Answer is %d\n',answer)
pracfn
fprintf('Answer is %d\n',answer)
end

2Z Assumea matrix variable maf, as in the following example:


mat=
4 2 4 3 2
1 3 1 0 S
2 4 4 0 2
Thefollowing for loop
[r, c] = size(mat);
fori= 1:r
sumprint(mat(i, :))
end
prints this result:
Thesumisnowl5
Thesumisnow25
Thesumisnow37
Write the function sumprint.
234 C HAPTER 6: NATLAB Programs

25 Thefollowing script land calls functions to:


prompt the user fora land area in acres
calculate and return the area in hectares and in square miles
print the results
One acre is 0.¢0¢7 hectares. One square mile is 6¢0 acres. Assume that the last
function, that prints, exists—you do not have to do anything for that function.
You are to write the entire function that calculates and returns the area in
hectares and in square miles, and write justa function stub forthe function that
prompts the user and reads. Do not write the actual contents of this function:
just writea stub!
land.m
inacres=askacres,
[sqmil, hectares] = convacres(inacres),
dispareas(inacres, sqmil, hectares) %Assume thisexists

26 The braking distance ofa car depends on its speed as the brakes are applied
and on the car's braking efficiency.A formula forthe braking distance is
2
d
* ' 2 Rg

wherebd is the braking distance,s is the car's speed,R is the braking efficiency,
and g is the acceleration due to gravity (9.81 j.A script has been written that calls
a function to prompt theuser fors and P, calls another function to calculate the
braking distance and callsa third function to print the braking distance ina
sentence format with one decimal place. You are to writea function stub forthe
function that prompts fors andP and the actual function definitions for the
other two functions.

[s, R] =promptSandR,
brakDist= calcbd(s, R),
printbd(brakDist)

27 Writea menu-d riven program toconverta time in seconds to other units


(minutes, hours, and so on). The main script will loop to continue until the user
chooses toexit. Each time in the loop, the script will generatea random time in
seconds, calla function to presenta menu ofoptions, and print the converted
time. The conversions must be made byindividual functions (e.g., one to convert
from seconds to minutes). All user-entries must be error-checked.
28 Writea menu-d riven program to investigate the constant a.M odel it after the
program that explores the constant e. Pi (ml is the ratio ofa circle's circum-
ference to its diameter. Many mathematicians have found ways toapproximate
x. For example, Machin's formula is:

1 1
= ¢ arctan 5 — arctan
3›
P rog ra m m in g StyleG u i de lin e s 233

Leibniz found that x can be approximated by:

This is calleda sum ofa series. There are six terms shown in this series. The
first term is ¢, the second term is —¢/3, the third term is ¢/5, and so forth. For
example, the menu-driven program might have the following options:
Print the result from Machin's formula.
Print the approximation using Leibniz” formula, allowing the user to specify
how many terms to use.
Print the approximation using Leibniz’ formula, looping untila “good”
approximation is found.
Exit the program.
29 Writea program tocalculate the position ofa projectile ata given time /. For an
initial velocity and angle of departure8s. theposition is given byx andy
coordinates as follows (note: the gravity constantg is 9.81 m/s2I:

x= vo cos(8o)!
y = vo sin(8o)f— 2gt2

The program should initialize the variables for the initial velocity, time, and
ang le of departure. It should then calla function to find thex and y coordinates
and then another function to print the results. If you have version R201 óa or
later, make thescript intoa live script.
This page intentionally left blank

You might also like