THMMY's "Optimization Techniques" course assignments.
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

47 rindas
1.5 KiB

  1. function [x_vals, f_vals, k] = method_newton(f, grad_f, hessian_f, xk, tol, max_iter, mode)
  2. % f: Objective function
  3. % grad_f: Gradient of the function
  4. % hessian_f: Hessian of the function
  5. % x0: Initial point [x0, y0]
  6. % tol: Tolerance for stopping criterion
  7. % max_iter: Maximum number of iterations
  8. % x_vals: Vector with the (x,y) values until minimum
  9. % f_vals: Vector with f(x,y) values until minimum
  10. % k: Number of iterations
  11. if strcmp(mode, 'armijo') == 1
  12. gamma_f = @(f, grad_f, dk, xk) gamma_armijo(f, grad_f, dk, xk);
  13. elseif strcmp(mode, 'minimized') == 1
  14. gamma_f = @(f, grad_f, dk, xk) gamma_minimized(f, grad_f, dk, xk);
  15. else % mode == 'fixed'
  16. gamma_f = @(f, grad_f, dk, xk) gamma_fixed(f, grad_f, dk, xk);
  17. end
  18. x_vals = xk; % Store iterations
  19. f_vals = f(xk(1), xk(2));
  20. for k = 1:max_iter
  21. grad = grad_f(xk(1), xk(2));
  22. % Check for convergence
  23. if norm(grad) < tol
  24. break;
  25. end
  26. hess = hessian_f(xk(1), xk(2));
  27. % Solve for search direction using Newton's step
  28. dk = - inv(hess) * grad;
  29. % Calculate gamma
  30. gk = gamma_f(f, grad_f, dk, xk);
  31. x_next = xk + gk * dk'; % Update step
  32. f_next = f(x_next(1), x_next(2));
  33. xk = x_next; % Update point
  34. x_vals = [x_vals; x_next]; % Store values
  35. f_vals = [f_vals; f_next]; % Store function values
  36. end
  37. end