This repository has been archived on 2024-10-22. You can view files and clone it, but cannot push or open issues or pull requests.
OM/Claudio_Maggioni_3/GD.m

34 lines
729 B
Mathematica
Raw Normal View History

2021-04-20 13:04:00 +00:00
function [xk, xs, gs] = GD(f, x0, max_itr, tol, bt)
2021-04-19 09:23:32 +00:00
syms x y;
xk = x0;
gf = gradient(f);
2021-04-20 13:04:00 +00:00
fl = matlabFunction(f);
gfl = matlabFunction(gf);
2021-04-19 09:23:32 +00:00
tnorm = norm(at(gf, xk), 2);
xs = zeros(size(x0, 1), max_itr + 1);
xs(:, 1) = x0;
gs = zeros(1, max_itr + 1);
gs(1) = tnorm;
k = 1;
while tnorm > tol && k <= max_itr
2021-04-20 13:04:00 +00:00
p = -gfl(xk(1), xk(2));
2021-04-19 09:23:32 +00:00
if bt
2021-04-20 13:04:00 +00:00
alpha = backtracking(fl, gfl, p, xk, 1, 0.9, 1e-4);
2021-04-19 09:23:32 +00:00
else
2021-04-20 13:04:00 +00:00
alpha = 1;
2021-04-19 09:23:32 +00:00
end
2021-04-20 13:04:00 +00:00
xk = xk + alpha * p;
2021-04-19 09:23:32 +00:00
k = k + 1;
xs(:, k) = xk;
2021-04-20 13:04:00 +00:00
tnorm = norm(gfl(xk(1), xk(2)), 2);
2021-04-19 09:23:32 +00:00
gs(k) = tnorm;
end
xs = xs(:, 1:k);
gs = gs(:, 1:k);
2021-04-20 13:04:00 +00:00
end