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/Newton.m

39 lines
856 B
Mathematica
Raw Normal View History

2021-04-20 13:04:00 +00:00
function [xk, xs, gs] = Newton(f, x0, max_itr, tol, bt)
2021-04-19 09:23:32 +00:00
syms x y;
xk = x0;
2021-04-20 13:04:00 +00:00
2021-04-19 09:23:32 +00:00
gf = gradient(f);
hf = hessian(f, [x, y]);
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 + 1
2021-04-20 13:04:00 +00:00
pk = - (at(hf, xk) \ at(gf, xk));
if bt
alpha = backtracking(fl, gfl, pk, xk, 1, 0.9, 1e-4);
else
alpha = 1;
end
xk = xk + alpha * pk;
2021-04-19 09:23:32 +00:00
tnorm = norm(at(gf, xk), 2);
k = k + 1;
xs(:, k) = xk;
gs(k) = tnorm;
end
xs = xs(:, 1:k);
gs = gs(:, 1:k);
2021-04-20 13:04:00 +00:00
end
function y = at(f, xk)
syms x y;
y = double(subs(f, [x, y], [xk(1), xk(2)]));
end