我有这个非线性无约束优化问题: f=2*pi*(x^2)+2*pi x y
我必须在 MatLab 中使用两种方法来解决它,牛顿法和梯度法。我编写了代码,但是我遇到了一些我无法修复的错误,所以我真的需要一些帮助,因为我必须用这些方法的结果制作一个图表,然后将它们进行比较。
梯度方法的代码:
这是问题给出的函数:
function f=functie()
syms x y;
f=(2*pi*(x^2))+(2*pi*x*y);
end
这是给定点的函数评估:
function y = feval_obj(x)
y=(2*pi*(x(1)^2))+(2*pi*x(1)*x(2));
end
这是该给定点的函数梯度:
function y = gradient_obj(val)
gradient_f = gradient(functie);
syms x y;
y = subs(gradient_f, [x, y], val);
end
我必须在问题的每次迭代中检查理想的步骤,所以我需要另一个函数来返回函数 f(x + alpha*d) 的值
function f = phi_obj(alpha, x, d)
f = feval_obj(x + alpha * d);
end
渐变方法的代码将是:
function xmin=gradient_method(x0,eps)
%Initializing of the vectors/matrix that we need
puncte_gradient=[]; %gradient points
puncte_iteratie=[]; %iteration points
valori_functie=[]; %function values
norme_gradienti=[]; %gradients norm
%I will use a vector g to keep the current gradient
x=x0;
g=gradient_obj(x);
while(norm(g)>eps)
g=gradient_obj(x);
puncte_gradient=[puncte_gradient g];
puncte_iteratie=[puncte_iteratie x];
valori_functie=[valori_functie; feval_obj(x)];
norme_gradienti=[norme_gradienti; norm(g)];
alpha=fminsearch(@(alpha) phi_obj(alpha,x,-g), 1);
x=x-alpha*g
end
xmin=x;
%This is the chart display of the data I get
t=1:length(valori_functie);
figure(1)
hold on
plot(t,norme_gradienti(t),'k','LineWidth',2);
hold off
figure(2)
hold on
plot(t,valori_functie(t),'k','LineWidth',2);
hold off
% For drawing the contour lines and the gradient method_s evolution we have:
[x1,x2]=meshgrid([1.2:0.01:2.8],[0.4:0.01:1.6]);
z=(2*pi*(x1^2))+(2*pi*x1*x2);
figure(3)
hold on
contour(x1,x2,z,valori_functie);
plot3(puncte_iteratie(1,:),puncte_iteratie(2,:),valori_functie,'r');
scatter3(puncte_iteratie(1,:),puncte_iteratie(2,:),valori_functie,'filled');
hold off
end
一旦我设法解决这个问题,我将使用牛顿方法更新帖子。那么有人知道为什么我会出错吗?为了找到理想的步长,x0应该是一个初始值,eps应该是容差。(如果梯度的范数大于算法应该停止的容差)。