先建立一维搜索的m文件:minWP.m如下
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [x,minf]=minWP(f,XMAX,c1,c2,alpha,tol)
%一维搜索的Wolfe-Powell法
%作者:龚纯 王正林<<精通 Matlab 最优化计算>>
%f:目标函数
%XMAX:搜索最大值
%c1:可接受系数1
%c2:可接受系数2
%alpha:增大步长倍数
%tol:精度
%x:极小值点
%minf:极小值点处的函数值
format long
if nargin==5
tol=1.0e-6
end
if ~(c1>0)||~(c1<c2)||~(c2<1)||~(XMAX>卜烂0)||~(alpha>1)
error('参数不对')
end
var=findsym(f)
df=diff(f)
f0=subs(f,var,0)
df0=subs(df,var,0)
a=0
b=XMAX
if b<inf
t=(a+b)/2
else
t=10
end
while 1
ft=subs(f,var,t)
fu=f0+c1*t*df0
if ft<=fu
dft=subs(df,var,t)
dfl=c2*t*df0
if dft>dfl
x=t
break
else
a=t
if b==inf
t=t*alpha
else
t=(a+b)/2
end
continue
end
else
b=t
t=(a+b)/2
continue
end
end
minf=subs(f,var,t)
format short
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
然后建立最速下降法的m文件如下:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%minFD.m
function [x,minf]=minFD(f,x0,var,tol)
%最速下降法
%作者:龚纯 王正林《精通Matlab最优化计算》
%目标函数:f
%初始点:x0
%自变量向量:var
%精度:tol
%所求的驻点戚让:x
%驻点处的函数值
format long
if nargin==3
tol=1.0e-6
end
gradf=jacobian(f,var) %f的梯度
wucha=1
syms lamda
while wucha>tol
d=-subs(gradf,var,x0)
wucha=norm(d)
y=x0+lamda*d
yf=subs(f,var,y)
%l=minHJ(yf,0,100)
l=minWP(yf,10,0.2,0.6,2)
x1=x0+l*d
x0=x1
end
x=x1
minf=subs(f,var,x)
format short
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
保存后就可调用了:
>>clear
>>syms x1 x2
>>f=1.5*x1^2+0.5*x2^2-x1*x2-2*x1
f =
3/2*x1^2+1/2*x2^2-x1*x2-2*x1
>>[x,mf]=minFD(f,[-2 4],[x1,x2])
x =
1.00001.0000
mf =
-1.0000
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)