Write a matlabreg function called numgrains to find the


Problems 233

Commands and Functions

Fzero a function function that accepts a function handle or function defi nition as input and fi nds the function zero point nearest a specifi ed value

function identifi es an M-fi le as a function

global defi nes a variable that can be used in multiple sections of code

meshgrid maps two input vectors onto two two-dimensional matrices

nargin determines the number of input arguments in a function

nargout determines the number of output arguments from a function

pathtool opens the interactive path tool

varargin indicates that a variable number of arguments may be input to a function

KEY TERMS

anonymous

folding in-line

argument

function

input

argument

comments

function function

local variable

directory

function handle

M-file

file name

function name

nesting

folder

global variable

toolbox

 

PROBLEMS

Function M-Files

As you create functions in this section, be sure to comment them appropriately. Remember that, although many of these problems could be solved without a func-tion, the objective of this chapter is to learn to write and use functions. Each of these functions (except for the anonymous functions) must be created in its own M-file and then called from the command window or a script M-file program.

6.1 As described in Example 6.2, metals are actually crystalline materials. Metal crystals are called grains. When the average grain size is small, the metal is strong; when it is large, the metal is weaker. Since every crystal in a particu-lar sample of metal is a different size, it isn't obvious how we should describe the average crystal size. The American Society for Testing and Materials (ASTM) has developed the following correlation for standardizing grain-size measurements:

N 5 2n 2 1

The ASTM grain size (n) is determined by looking at a sample of a metal under a microscope at a magnification of 100 3 (100 power). The number of grains in a 1-square-inch area (actual dimensions of 0.01 in 3 0.01 in) is estimated (N) and used in the preceding equation to find the ASTM grain size.

(a) Write a MATLAB® function called num_grains to find the number of grains in a 1-square-inch area (N) at 100 3 magnification when the ASTM grain size is known.

234 Chapter 6 User-Defi ned Functions

(b) Use your function to find the number of grains for ASTM grain sizes n 5 10 to 100.

(c) Create a plot of your results.

6.2 Perhaps the most famous equation in physics is

E 5 mc2

which relates energy E to mass m. The speed of light in a vacuum, c, is the property that links the two together. The speed of light in a vacuum is 2.9979 3 108 m>s.

(a) Create a function called energy to find the energy corresponding to a given mass in kilograms. Your result will be in joules, since 1 kg m2 >s2 5 1 J.

(b) Use your function to find the energy corresponding to masses from 1 kg to 106 kg. Use the logspace function (consult help logspace) to create an appropriate mass vector.

(c) Create a plot of your results. Try using different logarithmic plotting approaches (e.g., semilogy, semilogx, and loglog) to determine the best way to graph your results.

6.3 The future-value-of-money formula relates how much a current investment will be worth in the future, assuming a constant interest rate.

FV 5 PV 3 11 1 I2n

where

FV is the future value

PV is the present value or investment

I is the interest rate expressed as a fractional amount per compounding period-i.e., 5% is expressed as .05 n is the number of compounding periods.

(a) Create a MATLAB® function called future_value with three inputs: the investment (present value), the interest rate expressed as a fraction, and the number of compounding periods.

(b) Use your function to determine the value of a $1000 investment in 10 years, assuming the interest rate is 0.5% per month, and the interest is compounded monthly.

6.4 In freshman chemistry, the relationship between moles and mass is introduced:

n 5 m MW where n 5 number of moles of a substance m 5 mass of the substance MW 5 molecular weight (molar mass) of the substance.

(a) Create a function M-file called nmoles that requires two vector inputs- the mass and molecular weight-and returns the corresponding num-ber of moles. Because you are providing vector input, it will be necessary to use the meshgrid function in your calculations.

Problems 235

(b) Test your function for the compounds shown in the following table, for masses from 1 to 10 g:

Compound Molecular Weight (Molar Mass)

Benzene 78.115 g/mol

Ethyl alcohol 46.07 g/mol

Refrigerant R134a 102.3 g/mol (tetrafl uoroethane)

Your result should be a 10 3 3 matrix.

6.5 By rearranging the preceding relationship between moles and mass, you can find the mass if you know the number of moles of a compound:

m 5 n 3 MW

(a) Create a function M-file called mass that requires two vector inputs- the number of moles and the molecular weight-and returns the cor-responding mass. Because you are providing vector input, it will be necessary to use the meshgrid function in your calculations.

(b) Test your function with the compounds listed in the previous problem, for values of n from 1 to 10.

6.6 The distance to the horizon increases as you climb a mountain (or a hill). The expression

d 5 22rh 1 h2

where d 5 distance to the horizon r 5 radius of the earth h 5 height of the hill can be used to calculate that distance. The distance depends on how high the hill is and on the radius of the earth (or another planetary body).

(a) Create a function M-file called distance 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 5 7926 miles

• Mars' diameter 5 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 5 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 h1t2 5 - 9.8 t2 1 125t 1 500 for t 7 0 2

(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 versus time for times from 0 to 30 seconds. Use an incre-ment 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 x 5 1 gt2 2 where g 5 acceleration due to gravity, 9.8 m>s2 t 5 time in seconds x 5 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 5 v 5 gt dt We can find the acceleration by taking the derivative again:

dv 5 a 5 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 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 1TF2, degrees Celsius 1TC2, kelvins 1TK2, and degrees Rankine 1TR2, respectively:

Problems 237

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 Fahrenheit 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 a 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 pro-portional to the atmospheric pressure, or

P 5 rgh

where P is the pressure, r 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>m3. On the surface of the earth, the acceleration due to gravity, g, is approximately 9.8 m>s2. 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 mkg 1

(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 5 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 5 mCp DT where m 5 mass of the water, in grams

Cp = heat capacity of water, 1 cal/g K DT 5 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:

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 2 5x 2 3 1 ex

(b) Use the fplot function to create a plot from x 5 2 5 to x 5 1 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 function, 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 M-file 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:

(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 ground (i.e., when the function value is zero). The fzero function is an example of a function function, since it requires a function or func-tion handle as input. The syntax is 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).

Problems 239

Subfunctions

6.15 In Problem 6.10 you were asked to create and use three different temperature-conversion functions, based on the following conversion equations:

Recreate Problem 6.10 using nested subfunctions. The primary function should be called temperature_conversions and should include the 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 col-umn 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 M-file.


Attachment:- Chapter_6_-_Homework.pdf

Request for Solution File

Ask an Expert for Answer!!
MATLAB Programming: Write a matlabreg function called numgrains to find the
Reference No:- TGS01558388

Expected delivery within 24 Hours