matlab函数求极值matlab函数求极值
* * 函数的极值 1、一元函数的极值 函数命令:fminbnd 调用格式:[x,feval,exitflag,output]=fminbnd(fun,x1,x2,options) %求fun在区间(x1,x2)上的极值. 返回值: x:函数fun在(x1,x2)内的极值点 feval:求得函数的极值 exitflag: exitflag>0,函数收敛于解x处 exitflag=0,已达最大迭代次数 exiflag<0,函数在计算区间内不收敛. 例1:求函数 在 上的极小值. fun=inline('(x+pi)*exp(abs(sin(x+pi)))') [x,feval,exitflag,output]=fminbnd(fun,-pi/2,pi/2) fun = Inline function: fun(x) = (x+pi)*exp(abs(sin(x+pi))) x = -1.2999e-005 feval = 3.1416 exitflag = 1 output = iterations: 21 funcCount: 22 algorithm: 'golden section search, parabolic interpolation' message: [1x112 char] xx=-pi/2:pi/200:pi/2; yxx=(xx+pi).*exp(abs(sin(xx+pi))); plot(xx,yxx) xlabel('x'),grid on % 可以用命令[xx,yy]=ginput(1) 从局部图上取出极值点及相应函数值 例2:求解函数humps的极小值. type humps %humps 是一个Matlab提供的M函数文件 function [out1,out2] = humps(x) %HUMPS A function used by QUADDEMO, ZERODEMO and FPLOTDEMO. % Y = HUMPS(X) is a function with strong maxima near x = .3 % and x = .9. % % [X,Y] = HUMPS(X) also returns X. With no input arguments, % HUMPS uses X = 0:.05:1. % % Example: % plot(humps) % % See QUADDEMO, ZERODEMO and FPLOTDEMO. % Copyright 1984-2002 The MathWorks, Inc. % $Revision: 5.8 $ $Date: 2002/04/15 03:34:07 $ if nargin==0, x = 0:.05:1; end y = 1 ./ ((x-.3).^2 + .01) + 1 ./ ((x-.9).^2 + .04) - 6; if nargout==2, out1 = x; out2 = y; else out1 = y; end [x,y]=fminbnd(@humps,0.5,0.8) x = 0.6370 y = 11.2528 xx=0:0.001:2; yy=humps(xx); plot(xx,yy) 例3:求 在(0,1)内的极小值. type myfunmin1 %显示M文件内容 function f=myfunmin1(x) f=x.^x; [x,y]=fminbnd(@myfunmin1,0,1) x = 0.3679 y = 0.6922 xx=0:0.001:1; yy=myfunmin1(xx); plot(xx,yy) [x,y]=fminbnd('x.^x',0,1) x = 0.3679 y = 0.6922 2、 多元函数的极值 函数命令:fminsearch 调用格式:[x,feval,exitflag,output]=fminsearch(fun,x0,optipons) % 求在x0附近的极值 例4:求 的极小值. type myfunmin2 function f=myfunmin2(v) x=v(1); y=v(2); f=100*(y-x.^2).^2+(1-x).^2; [sx,sfeval]=fminsearch(@myfunmin2,[1 1]) sx