PASSING FUNCTIONS TO M-FILES
3.5.2 Function Functions
Function functions are functions that operate on other functions which are passed to it as input arguments. The function that is passed to the function function is referred to as the passed function . A simple example is the built-in function fplot , which plots the graphs of functions. A simple representation of its syntax is fplotfunc,lims where func is the function being plotted between the x-axis limits specified by lims = [ xmin xmax ]. For this case, func is the passed function. This function is “smart” in that it automatically analyzes the function and decides how many values to use so that the plot will exhibit all the function’s features. Here is an example of how fplot can be used to plot the velocity of the free-falling bungee jumper. The function can be created with an anonymous function: vel=t ... sqrt9.8168.10.25tanhsqrt9.810.2568.1t; We can then generate a plot from t = 0 to 12 as fplotvel,[0 12] The result is displayed in Fig. 3.3. Note that in the remainder of this book, we will have many occasions to use MATLAB’s built-in function functions. As in the following example, we will also be developing our own. EXAMPLE 3.8 Building and Implementing a Function Function Problem Statement. Develop an M-file function function to determine the average value of a function over a range. Illustrate its use for the bungee jumper velocity over the range from t = 0 to 12 s: v t = gm c d tanh gc d m t where g = 9.81, m = 68.1, and c d = 0.25. Solution. The average value of the function can be computed with standard MATLAB commands as t=linspace0,12; v=sqrt9.8168.10.25tanhsqrt9.810.2568.1t; meanv ans = 36.0870 Inspection of a plot of the function Fig. 3.3 shows that this result is a reasonable estimate of the curve’s average height. FIGURE 3.3 A plot of velocity versus time generated with the fplot function. 60 50 40 30 20 10 2 4 6 8 10 12 3.5 PASSING FUNCTIONS TO M-FILES 77 We can write an M-file to perform the same computation: function favg = funcavga,b,n funcavg: average function height favg=funcavga,b,n: computes average value of function over a range input: a = lower bound of range b = upper bound of range n = number of intervals output: favg = average value of function x = linspacea,b,n; y = funcx; favg = meany; end function f = funct f=sqrt9.8168.10.25tanhsqrt9.810.2568.1t; end The main function first uses linspace to generate equally spaced x values across the range. These values are then passed to a subfunction func in order to generate the cor- responding y values. Finally, the average value is computed. The function can be run from the command window as funcavg 0,12,60 ans = 36.0127 Now let’s rewrite the M-file so that rather than being specific to func , it evaluates a nonspecific function name f that is passed in as an argument: function favg = funcavg f,a,b,n funcavg: average function height favg=funcavgf,a,b,n: computes average value of function over a range input: f = function to be evaluated a = lower bound of range b = upper bound of range n = number of intervals output: favg = average value of function x = linspacea,b,n; y = fx; favg = meany; Because we have removed the subfunction func , this version is truly generic. It can be run from the command window as vel=t ... sqrt9.8168.10.25tanhsqrt9.810.2568.1t; funcavgvel,0,12,60 ans = 36.0127 To demonstrate its generic nature, funcavg can easily be applied to another case by merely passing it a different function. For example, it could be used to determine the aver- age value of the built-in sin function between 0 and 2π as funcavgsin,0,2pi,180 ans = -6.3001e-017 Does this result make sense? We can see that funcavg is now designed to evaluate any valid MATLAB expression. We will do this on numerous occasions throughout the remainder of this text in a number of contexts ranging from nonlinear equation solving to the solution of differential equations.3.5.3 Passing Parameters
Recall from Chap. 1 that the terms in mathematical models can be divided into dependent and independent variables, parameters, and forcing functions. For the bungee jumper model, the velocity v is the dependent variable, time t is the independent variable, the mass m and drag coefficient c d are parameters, and the gravitational constant g is the forcing function. It is commonplace to investigate the behavior of such models by per- forming a sensitivity analysis. This involves observing how the dependent variable changes as the parameters and forcing functions are varied. In Example 3.8, we developed a function function, funcavg , and used it to determine the average value of the bungee jumper velocity for the case where the parameters were set at m = 68.1 and c d = 0.25. Suppose that we wanted to analyze the same function, but with different parameters. Of course, we could retype the function with new values for each case, but it would be preferable to just change the parameters. As we learned in Sec. 3.5.1, it is possible to incorporate parameters into anonymous functions. For example, rather than “wiring” the numeric values, we could have done the following: m=68.1;cd=0.25; vel=t sqrt9.81mcdtanhsqrt9.81cdmt; funcavgvel,0,12,60 ans = 36.0127 However, if we want the parameters to take on new values, we must recreate the anony- mous function. MATLAB offers a better alternative by adding the term varargin as the function function’s last input argument. In addition, every time the passed function is invoked within the function function, the term varargin{:} should be added to the end of its argument list note the curly brackets. Here is how both modifications can be implemented for funcavg omitting comments for conciseness: function favg = funcavgf,a,b,n,varargin x = linspacea,b,n; y = fx,varargin{:}; favg = meany; When the passed function is defined, the actual parameters should be added at the end of the argument list. If we used an anonymous function, this can be done as in vel=t,m,cd sqrt9.81mcdtanhsqrt9.81cdmt; When all these changes have been made, analyzing different parameters becomes easy. To implement the case where m = 68.1 and c d = 0.25, we could enter funcavgvel,0,12,60,68.1,0.25 ans = 36.0127 An alternative case, say m = 100 and c d = 0.28, could be rapidly generated by merely changing the arguments: funcavgvel,0,12,60,100,0.28 ans = 38.9345 3.6 CASE STUDY 793.6 CASE STUDY BUNGEE JUMPER VELOCITY
Background. In this section, we will use MATLAB to solve the free-falling bungee jumper problem we posed at the beginning of this chapter. This involves obtaining a solu- tion of dv dt = g − c d m v |v| Recall that, given an initial condition for time and velocity, the problem involved iter- atively solving the formula, v i +1 = v i + dv i dt t Now also remember that to attain good accuracy, we would employ small steps. Therefore, we would probably want to apply the formula repeatedly to step out from our initial time to attain the value at the final time. Consequently, an algorithm to solve the problem would be based on a loop. Solution. Suppose that we started the computation at t = 0 and wanted to predict velocity at t = 12 s using a time step of t = 0.5 s. We would therefore need to apply the iterative equation 24 times—that is, n = 12 0.5 = 24 where n = the number of iterations of the loop. Because this result is exact i.e., the ratio is an integer, we can use a for loop as the basis for the algorithm. Here’s an M-file to do this including a subfunction defining the differential equation: function vend = velocity1dt, ti, tf, vi velocity1: Euler solution for bungee velocity vend = velocity1dt, ti, tf, vi Euler method solution of bungee jumper velocity input: dt = time step s ti = initial time s tf = final time s vi = initial value of dependent variable ms output: vend = velocity at tf ms t = ti; v = vi; n = tf - ti dt; for i = 1:n dvdt = derivv; v = v + dvdt dt; t = t + dt; end vend = v; end function dv = derivv dv = 9.81 - 0.25 68.1 vabsv; end This function can be invoked from the command window with the result: velocity10.5,0,12,0 ans = 50.9259 Note that the true value obtained from the analytical solution is 50.6175 Exam- ple 3.1. We can then try a much smaller value of dt to obtain a more accurate numeri- cal result: velocity10.001,0,12,0 ans = 50.6181 Although this function is certainly simple to program, it is not foolproof. In partic- ular, it will not work if the computation interval is not evenly divisible by the time step. To cover such cases, a while . . . break loop can be substituted in place of the shaded area note that we have omitted the comments for conciseness:3.6 CASE STUDY continued
Parts
» Applied Numerical Methods with MATLAB fo
» Motivation 1 1.2 Part Organization 2 Overview 123 2.2 Part Organization 124
» Overview 205 3.2 Part Organization 207 Overview 321 4.2 Part Organization 323
» Overview 459 5.2 Part Organization 460 Applied Numerical Methods with MATLAB fo
» New Chapters. Overview 547 6.2 Part Organization 551
» New Content. Overview 547 6.2 Part Organization 551
» New Homework Problems. Overview 547 6.2 Part Organization 551
» Numerical methods greatly expand the
» Numerical methods allow you to use
» PART ORGANIZATION Applied Numerical Methods with MATLAB fo
» CONSERVATION LAWS IN ENGINEERING AND SCIENCE
» NUMERICAL METHODS COVERED IN THIS BOOK
» CASE STUDY IT’S A REAL DRAG CASE STUDY continued
» CASE STUDY continued Applied Numerical Methods with MATLAB fo
» Use calculus to verify that Eq. 1.9 is a solution of
» Use calculus to solve Eq. 1 for the case where the ini-
» The following information is available for a bank account:
» Rather than the nonlinear relationship of Eq. 1.7, you
» For the free-falling bungee jumper with linear drag
» For the second-order drag model Eq. 1.8, compute the
» The amount of a uniformly distributed radioactive con-
» A storage tank Fig. P contains a liquid at depth y
» For the same storage tank described in Prob. 1.9, sup-
» Apply the conservation of volume see Prob. 1.9 to sim-
» THE MATLAB ENVIRONMENT ASSIGNMENT
» MATHEMATICAL OPERATIONS Applied Numerical Methods with MATLAB fo
» GRAPHICS Applied Numerical Methods with MATLAB fo
» OTHER RESOURCES Applied Numerical Methods with MATLAB fo
» CASE STUDY EXPLORATORY DATA ANALYSIS CASE STUDY continued
» Manning’s equation can be used to compute the veloc-
» It is general practice in engineering and science that
» You contact the jumpers used to generate the data in
» Figure Pa shows a uniform beam subject to a lin-
» M-FILES Applied Numerical Methods with MATLAB fo
» INPUT-OUTPUT Applied Numerical Methods with MATLAB fo
» STRUCTURED PROGRAMMING Applied Numerical Methods with MATLAB fo
» NESTING AND INDENTATION Applied Numerical Methods with MATLAB fo
» PASSING FUNCTIONS TO M-FILES
» CASE STUDY BUNGEE JUMPER VELOCITY CASE STUDY continued
» Economic formulas are available to compute annual
» Two distances are required to specify the location of a
» Develop an M-file to determine polar coordinates as
» Develop an M-file function that is passed a numeric
» Manning’s equation can be used to compute the velocity
» The volume V of liquid in a hollow horizontal cylinder of
» Develop a vectorized version of the following code:
» Based on Example 3.6, develop a script to produce an
» ERRORS Applied Numerical Methods with MATLAB fo
» Digital computers have magnitude and precision limits on their ability to represent
» Arithmetic Manipulations of Computer Numbers
» TRUNCATION ERRORS Applied Numerical Methods with MATLAB fo
» TOTAL NUMERICAL ERROR Applied Numerical Methods with MATLAB fo
» BLUNDERS, MODEL ERRORS, AND DATA UNCERTAINTY
» a Applied Numerical Methods with MATLAB fo
» OVERVIEW Applied Numerical Methods with MATLAB fo
» ROOTS IN ENGINEERING AND SCIENCE
» GRAPHICAL METHODS Applied Numerical Methods with MATLAB fo
» BRACKETING METHODS AND INITIAL GUESSES
» BISECTION Applied Numerical Methods with MATLAB fo
» FALSE POSITION Applied Numerical Methods with MATLAB fo
» CASE STUDY GREENHOUSE GASES AND RAINWATER CASE STUDY continued
» Locate the first nontrivial root of sinx = x
» Determine the positive real root of lnx
» A total charge Q is uniformly distributed around a ring-
» For fluid flow in pipes, friction is described by a di-
» Perform the same computation as in Prob. 5.22, but for
» SIMPLE FIXED-POINT ITERATION Applied Numerical Methods with MATLAB fo
» NEWTON-RAPHSON Applied Numerical Methods with MATLAB fo
» SECANT METHODS Applied Numerical Methods with MATLAB fo
» BRENT’S METHOD Applied Numerical Methods with MATLAB fo
» MATLAB FUNCTION: Applied Numerical Methods with MATLAB fo
» POLYNOMIALS Applied Numerical Methods with MATLAB fo
» CASE STUDY PIPE FRICTION CASE STUDY continued
» CASE STUDY continued CASE STUDY continued
» Use a fixed-point iteration and b the Newton-
» Use a the Newton-Raphson method and b the modi-
» Develop an M-file for the secant method. Along with
» Develop an M-file for the modified secant method.
» Differentiate Eq. E6.4.1 to get Eq. E6.4.2. a
» Perform the identical MATLAB operations as those
» In control systems analysis, transfer functions are
» Use the Newton-Raphson method to find the root of Given a
» INTRODUCTION AND BACKGROUND Applied Numerical Methods with MATLAB fo
» MULTIDIMENSIONAL OPTIMIZATION Applied Numerical Methods with MATLAB fo
» CASE STUDY EQUILIBRIUM AND MINIMUM POTENTIAL ENERGY
» Employ the following methods to find the minimum of
» Consider the following function:
» Develop a single script to a generate contour and
» The head of a groundwater aquifer is described in
» Recent interest in competitive and recreational cycling
» The normal distribution is a bell-shaped curve defined by
» Use the Applied Numerical Methods with MATLAB fo
» Given the following function:
» The specific growth rate of a yeast that produces an
» A compound A will be converted into B in a stirred
» Develop an M-file to locate a minimum with the
» Develop an M-file to implement parabolic interpola-
» Pressure measurements are taken at certain points
» The trajectory of a ball can be computed with
» The deflection of a uniform beam subject to a linearly
» The torque transmitted to an induction motor is a func-
» The length of the longest ladder that can negotiate
» MATRIX ALGEBRA OVERVIEW Applied Numerical Methods with MATLAB fo
» SOLVING LINEAR ALGEBRAIC EQUATIONS WITH MATLAB
» CASE STUDY CURRENTS AND VOLTAGES IN CIRCUITS CASE STUDY continued
» Five reactors linked by pipes are shown in Fig. P.
» SOLVING SMALL NUMBERS OF EQUATIONS
» MATLAB M-file: Operation Counting
» PIVOTING Applied Numerical Methods with MATLAB fo
» TRIDIAGONAL SYSTEMS Applied Numerical Methods with MATLAB fo
» CASE STUDY MODEL OF A HEATED ROD CASE STUDY continued
» Given the system of equations
» Given the equations Applied Numerical Methods with MATLAB fo
» An electrical engineer supervises the production of three
» Develop an M-file function based on Fig. 9.5 to im-
» GAUSS ELIMINATION AS LU FACTORIZATION
» CHOLESKY FACTORIZATION Applied Numerical Methods with MATLAB fo
» MATLAB LEFT DIVISION Applied Numerical Methods with MATLAB fo
» Use Cholesky factorization to determine [U] so that THE MATRIX INVERSE
» Norms and Condition Number in MATLAB
» CASE STUDY INDOOR AIR POLLUTION CASE STUDY continued
» Determine the matrix inverse for the system described
» Determine A Applied Numerical Methods with MATLAB fo
» Determine the Frobenius and row-sum norms for the
» Use MATLAB to determine the spectral condition num-
» Besides the Hilbert matrix, there are other matrices
» Use MATLAB to determine the spectral condition
» Repeat Prob. 11.10, but for the case of a six-
» The Lower Colorado River consists of a series of four a
» A chemical constituent flows between three reactors a
» LINEAR SYSTEMS: GAUSS-SEIDEL Applied Numerical Methods with MATLAB fo
» NONLINEAR SYSTEMS Applied Numerical Methods with MATLAB fo
» CASE STUDY CHEMICAL REACTIONS
» Use the Gauss-Seidel method to solve the following
» Repeat Prob. 12.3 but use Jacobi iteration.
» The following system of equations is designed to de-
» Solve the following system using three iterations with a
» MATHEMATICAL BACKGROUND Applied Numerical Methods with MATLAB fo
» PHYSICAL BACKGROUND Applied Numerical Methods with MATLAB fo
» THE POWER METHOD Applied Numerical Methods with MATLAB fo
» CASE STUDY EIGENVALUES AND EARTHQUAKES CASE STUDY continued
» Repeat Example but for three masses with the m’s =
» Use the power method to determine the highest eigen-
» Use the power method to determine the lowest eigen-
» Derive the set of differential equations for a three
» Consider the mass-spring system in Fig. P. The fre-
» STATISTICS REVIEW Applied Numerical Methods with MATLAB fo
» RANDOM NUMBERS AND SIMULATION
» LINEAR LEAST-SQUARES REGRESSION Applied Numerical Methods with MATLAB fo
» LINEARIZATION OF NONLINEAR RELATIONSHIPS
» COMPUTER APPLICATIONS Applied Numerical Methods with MATLAB fo
» CASE STUDY continued CASE STUDY continued CASE STUDY continued
» Using the same approach as was employed to derive
» Beyond the examples in Fig. 14.13, there are other
» The concentration of E. coli bacteria in a swimming
» Rather than using the base-e exponential model
» Determine an equation to predict metabolism rate as a
» On average, the surface area A of human beings is
» 2.12 2.15 2.20 2.22 2.23 2.26 2.30 Applied Numerical Methods with MATLAB fo
» An investigator has reported the data tabulated below
» Develop an M-file function to compute descriptive
» Modify the Applied Numerical Methods with MATLAB fo
» Develop an M-file function to fit a power model.
» Below are data taken from a batch reactor of bacterial
» A transportation engineering study was conducted to
» In water-resources engineering, the sizing of reser-
» Perform the same computation as in Example 14.3,
» POLYNOMIAL REGRESSION Applied Numerical Methods with MATLAB fo
» MULTIPLE LINEAR REGRESSION Applied Numerical Methods with MATLAB fo
» GENERAL LINEAR LEAST SQUARES
» QR FACTORIZATION AND THE BACKSLASH OPERATOR
» NONLINEAR REGRESSION Applied Numerical Methods with MATLAB fo
» CASE STUDY FITTING EXPERIMENTAL DATA CASE STUDY continued
» Fit a parabola to the data from Table 14.1. Determine
» Fit a cubic polynomial to the following data:
» Use multiple linear regression to derive a predictive
» As compared with the models from Probs. 15.5 and
» Use multiple linear regression to fit
» The following data were collected for the steady flow
» In Prob. 14.8 we used transformations to linearize
» Enzymatic reactions are used extensively to charac-
» The following data represent the bacterial growth in a
» Dynamic viscosity of water μ10
» Use the following set of pressure-volume data to find
» Environmental scientists and engineers dealing with
» It is known that the data tabulated below can be mod-
» hr Applied Numerical Methods with MATLAB fo
» CURVE FITTING WITH SINUSOIDAL FUNCTIONS
» CONTINUOUS FOURIER SERIES Applied Numerical Methods with MATLAB fo
» FOURIER INTEGRAL AND TRANSFORM
» DISCRETE FOURIER TRANSFORM DFT
» THE POWER SPECTRUM Applied Numerical Methods with MATLAB fo
» CASE STUDY SUNSPOTS Applied Numerical Methods with MATLAB fo
» The pH in a reactor varies sinusoidally over the course
» The solar radiation for Tucson, Arizona, has been tab-
» Use MATLAB to generate 64 points from the function
» INTRODUCTION TO INTERPOLATION Applied Numerical Methods with MATLAB fo
» NEWTON INTERPOLATING POLYNOMIAL Applied Numerical Methods with MATLAB fo
» LAGRANGE INTERPOLATING POLYNOMIAL Applied Numerical Methods with MATLAB fo
» INVERSE INTERPOLATION Applied Numerical Methods with MATLAB fo
» EXTRAPOLATION AND OSCILLATIONS Applied Numerical Methods with MATLAB fo
» Given the data Applied Numerical Methods with MATLAB fo
» Use the portion of the given steam table for super-
» The following data for the density of nitrogen gas ver-
» Ohm’s law states that the voltage drop V across an
» The acceleration due to gravity at an altitude y above
» INTRODUCTION TO SPLINES Applied Numerical Methods with MATLAB fo
» LINEAR SPLINES Applied Numerical Methods with MATLAB fo
» CUBIC SPLINES Applied Numerical Methods with MATLAB fo
» PIECEWISE INTERPOLATION IN MATLAB
» MULTIDIMENSIONAL INTERPOLATION Applied Numerical Methods with MATLAB fo
» CASE STUDY HEAT TRANSFER CASE STUDY continued
» A reactor is thermally stratified as in the following
» The following is the built-in
» Develop a plot of a cubic spline fit of the following
» The following data define the sea-level concentra- a
» NEWTON-COTES FORMULAS Applied Numerical Methods with MATLAB fo
» THE TRAPEZOIDAL RULE Applied Numerical Methods with MATLAB fo
» SIMPSON’S RULES Applied Numerical Methods with MATLAB fo
» HIGHER-ORDER NEWTON-COTES FORMULAS Applied Numerical Methods with MATLAB fo
» INTEGRATION WITH UNEQUAL SEGMENTS
» OPEN METHODS MULTIPLE INTEGRALS
» CASE STUDY COMPUTING WORK WITH NUMERICAL INTEGRATION CASE STUDY continued CASE STUDY continued
» Derive Eq. 19.4 by integrating Eq. 19.3. Evaluate the following integral:
» INTRODUCTION Applied Numerical Methods with MATLAB fo
» ROMBERG INTEGRATION Applied Numerical Methods with MATLAB fo
» GAUSS QUADRATURE Applied Numerical Methods with MATLAB fo
» MATLAB Functions: If the error is larger than the tolerance,
» CASE STUDY ROOT-MEAN-SQUARE CURRENT CASE STUDY continued
» Evaluate the following integral a analytically,
» Evaluate the following integral with a Romberg inte-
» Evaluate the double integral Compute work as described in Sec. 19.9, but use the
» Suppose that the current through a resistor is de-
» km 1100 1500 2450 3400 3630 4500 km 5380 6060 6280 6380 Applied Numerical Methods with MATLAB fo
» HIGH-ACCURACY DIFFERENTIATION FORMULAS Applied Numerical Methods with MATLAB fo
» RICHARDSON EXTRAPOLATION Applied Numerical Methods with MATLAB fo
» DERIVATIVES OF UNEQUALLY SPACED DATA
» DERIVATIVES AND INTEGRALS FOR DATA WITH ERRORS
» PARTIAL DERIVATIVES Applied Numerical Methods with MATLAB fo
» NUMERICAL DIFFERENTIATION WITH MATLAB
» CASE STUDY VISUALIZING FIELDS CASE STUDY continued
» Develop an M-file to obtain first-derivative estimates
» Develop an M-file function that computes first and
» A jet fighter’s position on an aircraft carrier’s runway
» Use the following data to find the velocity and accel-
» A plane is being tracked by radar, and data are taken
» Use regression to estimate the acceleration at each
» The normal distribution is defined as
» The following data were generated from the normal Use the
» The objective of this problem is to compare second-
» The pressure gradient for laminar flow through a con-
» The following data for the specific heat of benzene
» The specific heat at constant pressure c
» OVERVIEW IMPROVEMENTS OF EULER’S METHOD
» RUNGE-KUTTA METHODS Applied Numerical Methods with MATLAB fo
» SYSTEMS OF EQUATIONS Applied Numerical Methods with MATLAB fo
» CASE STUDY PREDATOR-PREY MODELS AND CHAOS
» Develop an M-file to solve a single ODE with Heun’s
» Develop an M-file to solve a single ODE with the
» Develop an M-file to solve a system of ODEs with
» Isle Royale National Park is a 210-square-mile archi-
» The motion of a damped spring-mass system
» Perform the same simulations as in Section 22.6 for ADAPTIVE RUNGE-KUTTA METHODS
» MULTISTEP METHODS Applied Numerical Methods with MATLAB fo
» STIFFNESS Applied Numerical Methods with MATLAB fo
» MATLAB APPLICATION: BUNGEE JUMPER WITH CORD
» CASE STUDY PLINY’S INTERMITTENT FOUNTAIN CASE STUDY continued
» Given Applied Numerical Methods with MATLAB fo
» THE SHOOTING METHOD Applied Numerical Methods with MATLAB fo
» FINITE-DIFFERENCE METHODS Applied Numerical Methods with MATLAB fo
» A cable is hanging from two supports at A and B
» In Prob. 24.16, the basic differential equation of the
Show more