强wolfe准则的FR共轭梯度算法matlab
时间: 2023-11-03 13:32:23 浏览: 95
以下是强Wolfe准则的FR共轭梯度算法的MATLAB代码:
%定义函数f及其梯度函数g
syms x1 x2
f = @(x1, x2) 100*(x2 - x1^2)^2 + (1 - x1)^2;
g = [diff(f, x1); diff(f, x2)];
%定义强Wolfe准则的线搜索函数
function [alpha, iter] = strong_wolfe(f, g, x, d, c1, c2, alpha_max, max_iter)
alpha = 0;
iter = 0;
phi = @(a) f(x(1)+a*d(1), x(2)+a*d(2));
phi_prime = @(a) g(1)*(x(1)+a*d(1)) + g(2)*(x(2)+a*d(2));
while iter < max_iter
phi_0 = f(x(1), x(2));
phi_prime_0 = g(1)*d(1) + g(2)*d(2);
alpha = (alpha_max + alpha)/2;
phi_alpha = phi(alpha);
if phi_alpha > phi_0 + c1*alpha*phi_prime_0 || (phi_alpha >= phi(alpha/2) && iter > 0)
alpha = zoom(f, g, x, d, alpha_max, alpha, c1, c2, max_iter);
return
end
phi_prime_alpha = phi_prime(alpha);
if abs(phi_prime_alpha) <= -c2*phi_prime_0
return
end
if phi_prime_alpha >= 0
alpha = zoom(f, g, x, d, alpha, alpha_max, c1, c2, max_iter);
return
end
iter = iter + 1;
end
end
%定义zoom函数
function alpha = zoom(f, g, x, d, alpha_low, alpha_high, c1, c2, max_iter)
iter = 0;
while iter < max_iter
alpha = (alpha_high + alpha_low)/2;
phi = @(a) f(x(1)+a*d(1), x(2)+a*d(2));
phi_prime = @(a) g(1)*(x(1)+a*d(1)) + g(2)*(x(2)+a*d(2));
phi_0 = f(x(1), x(2));
phi_alpha = phi(alpha);
phi_low = phi(alpha_low);
phi_prime_0 = g(1)*d(1) + g(2)*d(2);
phi_prime_alpha = phi_prime(alpha);
if phi_alpha > phi_0 + c1*alpha*phi_prime_0 || phi_alpha >= phi_low
alpha_high = alpha;
else
if abs(phi_prime_alpha) <= -c2*phi_prime_0
return
end
if phi_prime_alpha*(alpha_high - alpha_low) >= 0
alpha_high = alpha_low;
end
alpha_low = alpha;
end
iter = iter + 1;
end
end
%定义共轭梯度法函数
function [x, fval, iter] = fr_cg(f, g, x0, max_iter, tol)
x = x0;
g0 = double(subs(g, [x1, x2], [x(1), x(2)]));
d = -g0;
iter = 0;
while iter < max_iter
[alpha, ~] = strong_wolfe(f, g0, x, d, 1e-4, 0.9, 1, 1000);
x = x + alpha*d;
g1 = double(subs(g, [x1, x2], [x(1), x(2)]));
beta = (g1'*g1)/(g0'*g0);
d = -g1 + beta*d;
g0 = g1;
if norm(g0) < tol
break
end
iter = iter + 1;
end
fval = double(subs(f, [x1, x2], [x(1), x(2)]));
end
%设置初始点、最大迭代次数和容差
x0 = [-1.2; 1];
max_iter = 1000;
tol = 1e-6;
%调用共轭梯度法函数并输出结果
[x, fval, iter] = fr_cg(f, g, x0, max_iter, tol);
disp(['The minimum value of the function is ', num2str(fval), ' at x = [', num2str(x(1)), ', ', num2str(x(2)), '] with ', num2str(iter), ' iterations.']);
阅读全文