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
Claudio Maggioni (maggicl) ca2a294fc7 hw3: done MATLAB
2021-04-22 13:37:38 +02:00

33 lines
729 B
Matlab

function [xk, xs, gs] = GD(f, x0, max_itr, tol, bt)
syms x y;
xk = x0;
gf = gradient(f);
fl = matlabFunction(f);
gfl = matlabFunction(gf);
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
p = -gfl(xk(1), xk(2));
if bt
alpha = backtracking(fl, gfl, p, xk, 1, 0.9, 1e-4);
else
alpha = 1;
end
xk = xk + alpha * p;
k = k + 1;
xs(:, k) = xk;
tnorm = norm(gfl(xk(1), xk(2)), 2);
gs(k) = tnorm;
end
xs = xs(:, 1:k);
gs = gs(:, 1:k);
end