Using MATLAB (779505), страница 52
Текст из файла (страница 52)
. . . . 14-19Example: Double Integration . . . . . . . . . . . . . 14-2014Function FunctionsAll of the functions described in this chapter are called function functionsbecause they accept a function as an input arguments. You can pass such afunction either as a function handle or as an inline object that defines amathematical function. The function that is passed in is referred to as theobjective function.This chapter includes:Function SummaryA summary of some function functionsRepresenting Functions in MATLABSome guidelines for representing functions in MATLABPlotting Mathematical FunctionsA discussion about using fplot to plot mathematical functionsMinimizing Functions and Finding ZerosA discussion of high-level function functions that perform optimization-relatedtasksNumerical Integration (Quadrature)A discussion of the MATLAB quadrature functionsNote See the “Differential Equations” and “Sparse Matrices” chapters forinformation about the use of other function functions.Note For information about function handles, see the function_handle (@),func2str, and str2func reference pages, and the “Function Handles” sectionof “Programming and Data Types” in the MATLAB documentation.14-2Function SummaryFunction SummaryThe function functions are located in the MATLAB funfun directory.This table provides a brief description of the functions discussed in thischapter.
Related functions are grouped by category.Function SummaryCategoryFunctionDescriptionPlottingfplotPlot function.Optimizationand zero findingfminbndMinimize function of one variable withbound constraints.fminsearchMinimize function of several variables.fzeroFind zero of function of one variable.quadNumerically evaluate integral, adaptiveSimpson quadrature.quadlNumerically evaluate integral, adaptiveLobatto quadrature.dblquadNumerically evaluate double integral.Numericalintegration14-314Function FunctionsRepresenting Functions in MATLABMATLAB can represent mathematical functions by expressing them asMATLAB functions in M-files or as inline objects. For example, consider thefunction11f ( x ) = ------------------------------------------- + ------------------------------------------- – 622( x – 0.3 ) + 0.01 ( x – 0.9 ) + 0.04This function can be used as input to any of the function functions.As MATLAB FunctionsYou can find the function above in the M-file named humps.m.function y = humps(x)y = 1./((x - 0.3).^2 + 0.01) + 1./((x - 0.9).^2 + 0.04) - 6;To evaluate the function humps at 2.0, use @ to obtain a function handle forhumps, and then pass the function handle to feval.fh = @humps;feval(fh,2.0)ans =-4.8552As Inline ObjectsA second way to represent a mathematical function at the command line is bycreating an inline object from a string expression.
For example, you can createan inline object of the humps functionf = inline(‘1./((x-0.3).^2 + 0.01) + 1./((x-0.9).^2 + 0.04)-6’);You can then evaluate f at 2.0.f(2.0)ans =-4.8552You can also create functions of more than one argument with inline byspecifying the names of the input arguments along with the string expression.For example, the following function has two input arguments x and y.14-4Representing Functions in MATLABf= inline('y*sin(x)+x*cos(y)','x','y')f(pi,2*pi)ans =3.141614-514Function FunctionsPlotting Mathematical FunctionsThe fplot function plots a mathematical function between a given set of axeslimits.
You can control the x-axis limits only, or both the x- and y-axis limits.For example, to plot the humps function over the x-axis range [-5 5], usefplot(@humps,[-5 5])grid on100806040200−20−5−4−3−2−1012345You can zoom in on the function by selecting y-axis limits of -10 and 25, usingfplot(@humps,[-5 5 -10 25])grid on14-6Plotting Mathematical Functions2520151050−5−10−5−4−3−2−1012345You can also pass an inline for fplot to graph, as infplot(inline('2*sin(x+3)'),[-1 1])You can plot more than one function on the same graph with one call to fplot.If you use this with a function, then the function must take a column vector xand return a matrix where each column corresponds to each function,evaluated at each value of x.If you pass an inline object of several functions to fplot, the inline object alsomust return a matrix where each column corresponds to each functionevaluated at each value of x, as infplot(inline('[2*sin(x+3), humps(x)]'),[-5 5])which plots the first and second functions on the same graph.14-714Function Functions100806040200−20−5−4−3−2−1012345Note that the inlinef= inline('[2*sin(x+3), humps(x)]')evaluates to a matrix of two columns, one for each function, when x is a columnvector.f([1;2;3])returns-1.5136-1.9178-0.558814-816.0000-4.8552-5.6383Minimizing Functions and Finding ZerosMinimizing Functions and Finding ZerosMATLAB provides a number of high-level function functions that performoptimization-related tasks.
This section describes:• Minimizing a function of one variable• Minimizing a function of several variables• Setting minimization options• Finding a zero of a function of one variable• Converting your code to MATLAB Version 5 syntaxThe MATLAB optimization functions are:fminbndMinimize a function of one variable on a fixed intervalfminsearchMinimize a function of several variablesfzeroFind zero of a function of one variablelsqnonnegLinear least squares with nonnegativity constraintsoptimgetGet optimization options structure parameter valuesoptimsetCreate or edit optimization options parameter structureFor more optimization capabilities, see the Optimization Toolbox.Minimizing Functions of One VariableGiven a mathematical function of a single variable coded in an M-file, you canuse the fminbnd function to find a local minimizer of the function in a giveninterval.
For example, to find a minimum of the humps function in the range(0.3, 1), usex = fminbnd(@humps,0.3,1)which returnsx =0.6370You can ask for a tabular display of output by passing a fourth argumentcreated by the optimset command to fminbnd14-914Function Functionsx = fminbnd(@humps,0.3,1,optimset('Display','iter'))which gives the outputFunc-count123456789x0.5673760.7326240.4652480.6444160.64130.6376180.6369850.6370190.637052f(x)12.909813.774625.171411.269311.258311.252911.252811.252811.2528Procedureinitialgoldengoldenparabolicparabolicparabolicparabolicparabolicparabolicx =0.6370This shows the current value of x and the function value at f(x) each time afunction evaluation occurs.
For fminbnd, one function evaluation correspondsto one iteration of the algorithm. The last column shows what procedure isbeing used at each iteration, either a golden section search or a parabolicinterpolation.Minimizing Functions of Several VariablesThe fminsearch function is similar to fminbnd except that it handles functionsof many variables, and you specify a starting vector x0 rather than a startinginterval. fminsearch attempts to return a vector x that is a local minimizer ofthe mathematical function near this starting vector.To try fminsearch, create a function three_var of three variables, x, y, and z.function b = three_var(v)x = v(1);y = v(2);z = v(3);b = x.^2 + 2.5*sin(y) - z^2*x^2*y^2;Now find a minimum for this function using x = -0.6, y = -1.2, andz = 0.135 as the starting values.v = [-0.6 -1.2 0.135];14-10Minimizing Functions and Finding Zerosa = fminsearch(@three_var,v)a =0.0000-1.57080.1803Setting Minimization OptionsYou can specify control options that set some minimization parameters bycalling fminbnd with the syntaxx = fminbnd(fun,x1,x2,options)or fminsearch with the syntaxx = fminsearch(fun,x0,options)options is a structure used by the optimization functions.
Use optimset to setthe values of the options structure.options = optimset('Display','iter');fminbnd and fminsearch use only the options parameters shown in thefollowing table. See the optimset reference page for a complete list of theparameters that are used in the Optimization Toolbox.options.DisplayA flag that determines if intermediate steps in theminimization appear on the screen. If set to 'iter',intermediate steps are displayed; if set to 'off', nointermediate solutions are displayed, if set to final,displays just the final output.options.TolXThe termination tolerance for x. Its default value is1.e-4.options.TolFunThe termination tolerance for the function value.The default value is 1.e-4.
This parameter is usedby fminsearch, but not fminbnd.options.MaxIterMaximum number of iterations allowed.options.MaxFunEvalsThe maximum number of function evaluationsallowed. The default value is 500 for fminbnd and200*length(x0) for fminsearch.14-1114Function FunctionsThe number of function evaluations, the number of iterations, and thealgorithm are returned in the structure output when you provide fminbnd orfminsearch with a fourth output argument, as in[x,fval,exitflag,output] = fminbnd(@humps,0.3,1);or[x,fval,exitflag,output] = fminsearch(@three_var,v);Finding Zeros of FunctionsThe fzero function attempts to find a zero of one equation with one variable.You can call this function with either a one-element starting point or atwo-element vector that designates a starting interval.















