Exercises are:
Problems 239
(a) Create a function called distance.m to find the distance to the horizon.
Your function should accept two vector inputs-radius and height-and
should return the distance to the horizon. Don’t forget that you’ll need
to use meshgrid because your inputs are vectors.
(b) Create a MATLAB®
program that uses your distance function to find
the distance in miles to the horizon, both on the Earth and on Mars,
for hills from 0 to 10,000 feet. Remember to use consistent units in your
calculations. Note that
• Earth’s diameter = 7926 miles
• Mars’ diameter = 4217 miles
Report your results in a table. Each column should represent a different
planet, and each row a different hill height.
6.7 A rocket is launched vertically. At time t=0, the rocket’s engine shuts down.
At that time, the rocket has reached an altitude of 500 m and is rising at a
velocity of 125 m/s. Gravity then takes over. The height of the rocket as a
function of time is
h(t)
9.8
– 12 + 125t + 500 for t> 0
2
9,80
(a) Create a function called height that accepts time as an input and
returns the height of the rocket. Use your function in your solutions to
parts b and c.
(b) Plot height vs. time for times from 0 to 30 seconds. Use an increment of
0.5 second in your time vector.
(c) Find the time when the rocket starts to fall back to the ground. (The max
function will be helpful in this exercise.)
6.8 The distance a freely falling object travels is
1
?
X
where
g=acceleration due to gravity, 9.8 m/s?,
t= time in seconds, and
x= distance traveled in meters.
If you have taken calculus, you know that we can find the velocity of the
object by taking the derivative of the preceding equation. That is,
dx
= v= gt
dt
We can find the acceleration by taking the derivative again:
du
= a=g
dt
(a) Create a function called free_fall with a single input vector t that
returns values for distance x, velocity v, and acceleration g.
(b) Test your function with a time vector that ranges from 0 to 20 seconds.
6.9 Create a function called polygon that draws a polygon with any number
of sides. Your function should require a single input: the number of sides
6.2 Creating Your Own Toolbox of Functions 225
KEY IDEA
functions
Group your
together into toolboxes.
6.2 CREATING YOUR OWN TOOLBOX OF FUNCTIONS
When
you call a function in MATLAB®, the program first looks in the current folder
to see if the function is defined. If it can’t find the function listed there, it starts down
a predefined search path, looking for a file with the function name. To view the path
the program takes as it looks for files, select
Set Path
from the Home toolstrip or type
pathtool
in the command window (see Figure 6.7).
As you create more and more functions to use in your programming, you may wish
to modify the path to look in a directory where you’ve stored your own personal tools.
For example, suppose you have stored the degrees-to-radians and radians-
to-degrees functions created in Example 6.1 in a directory called My_functions.
You can add this directory (folder) to the path by selecting Add Folder from the
list of option buttons in the Set Path dialog window, as shown in Figure 6.7. You’ll
be prompted to either supply the folder location or browse to find it, as shown in
Figure 6.8.
MATLAB® now first looks into the current folder for function definitions, then
works down the modified search path, as shown in Figure 6.9.
Once you’ve added a folder to the path, the change applies only to the current
MATLAB® session, unless you save your changes permanently. Clearly, you should
never make permanent changes to a public computer. However, if someone else
has made changes you wish to reverse, you can select the default button as shown in
Figure 6.9 to return the search path to its original settings.
The path tool allows you to change the MATLAB® search path interactively;
however, the addpath function allows you to insert the logic to add a search path
MATLAB®
program. Consult
to any
Set Path
–
Х
Figure 6.7
The path tool allows
you to change where
MATLAB® looks for function
definitions.
All changes take effect immediately.
MATLAB search path:
Add Folder…
C:\Users\Holly\Documents\MATLAB
C:\MATLAB\SupportPackages\R2016a\appdata_a53461d4c162f12C
Add with Subfolders…
C:\MATLAB\SupportPackages\R2016a\toolbox\realtime\targets\lego
C:\MATLAB\SupportPackages\R2016a\toolbox\realtime targets\lego blocks
C:\MATLAB\SupportPackages\R2016a\toolbox\realtime targets\lego
blocks\me
C:\MATLAB\SupportPackages\R2016a\toolbox\realtime\targets\lego legodemos
C:\MATLAB\SupportPackages\R2016\toolbox\target\supportpackages\ev3
Move to Top
C:\MATLAB\SupportPackages\R2016a\toolbox\target\supportpackages\ev3\blox
C:\MATLAB\SupportPackages\R2016a\toolbox\target\supportpackageslev3\bloc
Move Up
C:\MATLAB\SupportPackages\R2016a\toolbox\target\supportpackages\ev3\ev3.
C:\MATLAB\SupportPackages\R2016a\toolbox\target\supportpackages\ev3\regi
Move Down
C:\MATLAB\SupportPackages\R2016a\toolbox\realtime targets ev3io
C:\MATLAB\SupportPackages\R2016a\toolbox\realtime targets\ev3iolev3io_exa
Move to Bottom
C:\MATLAB\SupportPackages\R2016a\toolbox\target\supportpackages\shared_1
C:\Program Files\MATLAB\R2016a\toolbox\matlab\datafun
C:\Program Files\MATLAB\R2016a\toolbox\matlab\datatypes
C:\Program Files\MATLAB\R2016\toolbox\matlablelfun
C:\Program Files\MATLAB\R2016a\toolbox\matlab elmat
Remove
Save
Close
Revert
Default
Help
240 Chapter 6 User-Defined Functions
desired. It should not return any value to the command window, but should
draw the requested polygon in polar coordinates.
Creating Your Own Toolbox
6.10 This problem requires you to generate temperature-conversion tables. Use
the following equations, which describe the relationships between tempera-
tures in degrees Fahrenheit (Tp), degrees Celsius (TC), kelvins (TK), and
degrees Rankine (TR), respectively:
TE = TR – 459.67°R
TE
TC + 32°F
TR
=
TK
You will need to rearrange these expressions to solve some of the problems.
(a) Create a function called F_to_K that converts temperatures in Fahr-
enheit to Kelvin. Use your function to generate a conversion table for
values from 0°F to 200°F.
(b) Create a function called C_to_R that converts temperatures in Celsius
to Rankine. Use your function to generate a conversion table from 0°C
to 100°C. Print 25 lines in the table. (Use the linspace function to
create your input vector.)
(c) Create a function called C_to_F that converts temperatures in Celsius
to Fahrenheit. Use your function to generate conversion table from
0°C to 100°C. Choose an appropriate spacing.
(d) Group your functions into a folder (directory) called my_temp_
conversions. Adjust the MATLAB® search path so that it finds your
folder. (Don’t save any changes on a public computer!)
Anonymous Functions and Function Handles
6.11 Barometers have been used for almost 400 years to measure pressure changes
in the atmosphere. The first known barometer was invented by Evangelista
Torricelli (1608–1647), a student of Galileo during his final years in Florence,
Italy. The height of a liquid in a barometer is directly proportional to the
atmospheric pressure, or
P=pgh
where P is the pressure, p is the density of the barometer fluid, and h is
the height of the liquid column. For mercury barometers, the density of
the fluid is 13,560 kg/mº. On the surface of the Earth, the acceleration
due to gravity, g, is approximately 9.8 m/s². Thus, the only variable in the
equation is the height of the fluid column, h, which should have the unit
of meters.
(a) Create an anonymous function P that finds the pressure if the value of
h is provided. The units of your answer will be
kg m
kg 1
=
Pa.
mus?
ms?
6.5 Subfunctions 229
6.5 SUBFUNCTIONS
Subfunctions can be created by grouping functions together in a single file. There
are two approaches: you can add subfunctions to a script (starting with R2016b), or
you can use multiple subfunctions in a primary function. Subfunctions can be used
to modularize your code and to make the primary code easier to read. They have
the disadvantage that they are only available from the primary file, and cannot be
used by other programs.
HINT
You should not attempt to create code using subfunctions until you have first
mastered simple functions.
6.5.1 Using Subfunctions in Other Functions
Each MATLAB® function has one primary function. The name of the M-file must
be the same as the primary function name. Thus, the primary function stored in the
M-file my_function.m must be named my_function. Subfunctions are added after
the primary function and can have any legitimate MATLAB® variable name. Figure
6.11 shows a very simple example of a function that both adds and subtracts two vec-
tors. The primary function is named subfunction_demo. The file includes two
subfunctions: add and subtract.
Notice in the editing window that the contents of each function are identified
with a gray bracket. Each code section can be either collapsed or expanded, to make
the contents easier to read, by clicking on the + or – sign included with the bracket.
MATLAB® uses the term “folding” for this functionality.
Example 6.5 demonstrates the use of a more complicated example.
* *
Editor – C:\Users\Holly\Documents General Matlab Book Files\Matlab Sth Edition Chapter 6 Chapter 6 Examples\subfunction_demo.m
Х
EDITOR
PUBLISH
VIEW
o
Run
Figure 6.11
MATLAB® allows the user
to create subfunctions
within a function M-file.
This file includes the
primary function,
subfunction_demo, and
two subfunctions add and
subtract.
FILE
La Find Files
Insert e. fx
Run Section
Compare Go To
Comment % 9
New Open Save
Breakpoints
Run and Advance
Run and
Print
Find Indent E
Advance
Time
NAVIGATE
EDIT
BREAKPOINTS
RUN
Chapter_5_Homework_4th_Edition.mx Untitled12 X EXAMPLE_6_2.M EXAMPLE_6_3.MX star.mx subfunction_demo.mx +
1 Çfunction (addition_result, subtraction_result]=subfunction_demo (x,y)
2 f this function both adds and subtracts the elements stored in two arrays
3 addition_result = add(x,y);
4 subtraction_result = subtract(x,y);
11
function result = add(x, y) & subfunction add
result = x + y;
8
9
10
function output = subtract(x,y) % subfunction subtract
output = x-y;
–
subfunction_demo / subtract
Ln 9
Col 55
Problems 241
(b) Create another anonymous function to convert pressure in Pa (Pascals) to
pressure in atmospheres (atm). Call the function Pa_to_atm. Note that
1 atm = 101,325 Pa.
(c) Use your anonymous functions to find the pressure for fluid heights
from 0.5 m to 1.0 m of mercury.
(d) Save your anonymous functions as .mat files
6.12 The energy required to heat water at constant pressure is approximately
equal to
E= mCp AT
where
m
= mass of the water, in grams,
Cp heat capacity of water, 1 cal/g K, and
AT= change in temperature, K.
(a) Create an anonymous function called heat to find the energy required
to heat 1 gram of water if the change in temperature is provided as the
input.
(b) Your result will be in calories:
cal 1
g
-K= cal
gK
Joules are the unit of energy used most often in engineering. Create
another anonymous function cal_to_J to convert your answer from
part (a) into joules. (There are 4.2 J/cal.)
(c) Save your anonymous functions as .mat files.
6.13. (a) Create an anonymous function called my_function, equal to
– x2 – 5x – 3 + e*.
(b) Use the fplot function to create a plot from x= -5 to x= +5. Recall
that the fplot function can accept a function handle as input.
(c) Use the fminbnd function to find the minimum function value in
this range. The fminbnd function is an example of a function func-
tion, since it requires a function or function handle as input. The
syntax is
fminbnd (function_handle, xmin, xmax)
Three inputs are required: the function handle, the minimum value of x,
and the maximum value of x. The function searches between the minimum
value of x and the maximum value of x for the point where the function
value is a minimum.
*
6.14 In Problem 6.7, you created an function called height to evaluate the
height of a rocket as a function of time. The relationship between time, t,
and height, h(t), is:
h(t)
9.8
-t? + 125t + 500 for t> 0
2
242 Chapter 6 User-Defined Functions
*
(a) Create a function handle to the height function called height_handle.
(b) Use height_handle as input to the fplot function, and create a
graph from 0 to 60 seconds.
(c) Use the fzero function to find the time when the rocket hits the
(i.e., when the function value is zero). The fzero function is an exam-
ple of a function function, since it requires a function or function handle
as input. The syntax is
ground
fzero (function_handle, x_guess)
The fzero function requires two inputs—a function handle, and your
guess as to the time value where the function is close to zero. You can
select a reasonable x_guess value by inspecting the graph created in
part (b).
Subfunctions
6.15 In Problem 6.10, you were asked to create and use three different tempera-
ture-conversion functions, based on the following conversion equations:
TE = TR – 459.67°R
TE
Tc + 32°F
TR
9
TK
5
Recreate Problem 6.10 using nested subfunctions. The primary function
should be called temperature_conversions and should include the
following subfunctions
F_to_K
C_to_R
C_to_F
Within the primary function, use the subfunctions to:
(a) Generate a conversion table for values from 0°F to 200°F. Include a
column for temperature in Fahrenheit and Kelvin.
(b) Generate a conversion table from 0°C to 100°C. Print 25 lines in the
table. (Use the linspace function to create your input vector.) Your
table should include a column for temperature in Celsius and Rankine.
(c) Generate a conversion table from 0°C to 100°C. Choose an appropriate
spacing. Include a column for temperature in Celsius and Fahrenheit.
Recall that you will need to call your primary function from the command
window, or from a script.