Using MATLAB (779505), страница 53
Текст из файла (страница 53)
If you give fzero astarting point x0, fzero first searches for an interval around this point wherethe function changes sign. If the interval is found, then fzero returns a valuenear where the function changes sign. If no such interval is found, fzeroreturns NaN. Alternatively, if you know two points where the function valuediffers in sign, you can specify this starting interval using a two-elementvector; fzero is guaranteed to narrow down the interval and return a valuenear a sign change.Use fzero to find a zero of the humps function near -0.2a = fzero(@humps,-0.2)a =-0.1316For this starting point, fzero searches in the neighborhood of -0.2 until it findsa change of sign between -0.10949 and -0.264.
This interval is then narroweddown to -0.1316. You can verify that -0.1316 has a function value very close tozero usinghumps(a)ans =8.8818e -16Suppose you know two places where the function value of humps differs in signsuch as x = 1 and x = -1. You can usehumps(1)14-12Minimizing Functions and Finding Zerosans =16humps(-1)ans =-5.1378Then you can give fzero this interval to start with and fzero then returns apoint near where the function changes sign. You can display information asfzero progresses withoptions = optimset('Display','iter');a = fzero(@humps,[-1 1],options)Func-count1123456789101112x-11-0.5138760.243062-0.473635-0.115287-0.150214-0.132562-0.131666-0.131618-0.131618-0.131618-0.131618f(x)-5.1377916-4.0223571.6382-3.837670.414441-0.423446-0.0226907-0.00114921.88371e-07-2.7935e-118.88178e-16-9.76996e-15Procedureinitialinitialinterpolationbisectioninterpolationbisectioninterpolationinterpolationinterpolationinterpolationinterpolationinterpolationinterpolationa =-0.1316The steps of the algorithm include both bisection and interpolation under theProcedure column.
If the example had started with a scalar starting pointinstead of an interval, the first steps after the initial function evaluationswould have included some search steps while fzero searched for an intervalcontaining a sign change.14-1314Function FunctionsYou can specify a relative error tolerance using optimset. In the call above,passing in the empty matrix causes the default relative error tolerance of epsto be used.14-14Minimizing Functions and Finding ZerosTipsOptimization problems may take many iterations to converge.
Mostoptimization problems benefit from good starting guesses. Providing goodstarting guesses improves the execution efficiency and may help locate theglobal minimum instead of a local minimum.Sophisticated problems are best solved by an evolutionary approach, wherebya problem with a smaller number of independent variables is solved first.Solutions from lower order problems can generally be used as starting pointsfor higher order problems by using an appropriate mapping.The use of simpler cost functions and less stringent termination criteria in theearly stages of an optimization problem can also reduce computation time.Such an approach often produces superior results by avoiding local minima.TroubleshootingBelow is a list of typical problems and recommendations for dealing with them.ProblemRecommendationThe solution found by fminbndor fminsearch does not appearto be a global minimum.There is no guarantee that you have a global minimum unlessyour problem is continuous and has only one minimum.Starting the optimization from a number of different startingpoints (or intervals in the case of fminbnd) may help to locatethe global minimum or verify that there is only one minimum.Use different methods, where possible, to verify results.Sometimes an optimizationproblem has values of x forwhich it is impossible toevaluate f.Modify your function to include a penalty function to give alarge positive value to f when infeasibility is encountered.The minimization routineappears to enter an infinite loopor returns a solution that is nota minimum (or not a zero in thecase of fzero).Your objective function (fun) may be returning Inf, NaN, orcomplex values.
The optimization routines expect only realnumbers to be returned. Any other values may causeunexpected results. Insert code into your objective functionM-file to verify that only real numbers are returned (use thefunctions isreal and isfinite).14-1514Function FunctionsConverting Your Optimization Code to MATLABVersion 5 SyntaxMost of the function names and calling sequences changed in Version 5 toaccommodate new functionality and to clarify the roles of the input and outputvariables.This table lists the optimization functions provided by MATLAB and indicatesthe functions whose names have changed in Version 5.Old (Version 4) NameNew (Version 5) Namefminfminbndfminsfminsearchfoptionsoptimget, optimsetfzerofzero (name unchanged)nnlslsqnonnegThis section:• Tells you how to override default parameter settings with the new optimsetand optimget functions.• Explains the reasons for the new calling sequences and explains how toconvert your code.In addition to the information in this section, consult the individual functionreference pages for information about the new functions and about thearguments they take.Using optimset and optimgetThe optimset function replaces foptions for overriding default parametersettings.
optimset creates an options structure that contains parameters usedin the optimization routines. If, on the first call to an optimization routine, theoptions structure is not provided, or is empty, a set of default parameters isgenerated. See the optimset reference page for details.14-16Minimizing Functions and Finding ZerosNew Calling SequencesVersion 5 of MATLAB makes these changes in the calling sequences:• Each function takes an options structure to adjust parameters to theoptimization functions (see optimset, optimget).• The new default output gives information if the function does not converge.(the Version 4 default was no output, Version 5 used 'final' as the default,the new default is options.display = 'notify').• Each function returns an exitflag that describes the termination state.• Each function now has an output structure that contains information aboutthe problem solution relevant to that function.The sections below describe how to convert from the old function names andcalling sequences to the new ones.
The calls shown are the most general cases,involving all possible input and output arguments. Note that many of thesearguments are optional. See the function reference pages for more information.Converting from fmin to fminbnd. In Version 4, you used this call to fmin.[X,OPTIONS] = fmin('FUN',x1,x2,OPTIONS,P1,P2,...);In Version 5, you call fminbnd like this.[X,FVAL,EXITFLAG,OUTPUT] = fminbnd(@FUN,x1,x2,...OPTIONS,P1,P2,...);Converting from fmins to fminsearch.
In Version 4, you used this call to fmins.[X,OPTIONS] = fmins('FUN',x0,OPTIONS,[],P1,P2,...);In Version 5, you call fminsearch like this.[X,FVAL,EXITFLAG,OUTPUT] = fminsearch(@FUN,x0,...OPTIONS,P1,P2,...);Converting to the new form of fzero. In Version 4, you used this call to fzero.X = fzero('F',X,TOL,TRACE,P1,P2,...);14-1714Function FunctionsIn Version 5, replace the TRACE and TOL arguments withif TRACE == 0,val = 'none';elseif TRACE == 1val = 'iter';endOPTIONS = optimset('Display',val,'TolX',TOL);Now call fzero like this.[X,FVAL,EXITFLAG,OUTPUT] = fzero(@F,X,OPTIONS,P1,P2,...);Converting from nnls to lsqnonneg.
In Version 4, you used this call to nnls.[X,LAMBDA] = nnls(A,b,tol);In Version 5, replace the tol argument withOPTIONS = optimset('Display','none','TolX',tol);Now call lsqnonneg like this.[X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA] =lsqnonneg(A,b,X0,OPTIONS);14-18Numerical Integration (Quadrature)Numerical Integration (Quadrature)The area beneath a section of a function F(x) can be determined by numericallyintegrating F(x), a process referred to as quadrature.
The MATLAB quadraturefunctions are:quadUse adaptive Simpson quadraturequadlUse adaptive Lobatto quadraturedblquadNumerically evaluate double integralTo integrate the function defined by humps.m from 0 to 1, useq = quad(@humps,0,1)q =29.8583Both quad and quadl operate recursively. If either method detects a possiblesingularity, it prints a warning.You can include a fourth argument for quad or quadl that specifies a relativeerror tolerance for the integration. If a nonzero fifth argument is passed to quador quadl, the function evaluations are traced.Two examples illustrate use of these functions:• Computing the length of a curve• Double integrationExample: Computing the Length of a CurveYou can use quad or quadl to compute the length of a curve.
Consider the curveparameterized by the equationsx ( t ) = sin ( 2t ),y ( t ) = cos ( t ),z(t) = twhere t ∈ [ 0, 3π ] .A three-dimensional plot of this curve ist = 0:0.1:3*pi;plot3(sin(2*t),cos(t),t)14-1914Function FunctionsThe arc length formula says the length of the curve is the integral of the normof the derivatives of the parameterized equations3π∫224 cos ( 2t ) + sin ( t ) + 1 dt0The function hcurve computes the integrandfunction f = hcurve(t)f = sqrt(4*cos(2*t).^2 + sin(t).^2 + 1);Integrate this function with a call to quadlen = quad(@hcurve,0,3*pi)len =1.7222e+01The length of this curve is about 17.2.Example: Double IntegrationConsider the numerical solution ofymaxxmax∫∫yminxminf ( x, y ) dx dyFor this example f ( x, y ) = y sin ( x ) + x cos ( y ) .















