THMMY's "Optimization Techniques" course assignments.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lev_mar.m 1.5 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. function [x_vals, f_vals, k] = lev_mar(f, grad_f, hessian_f, m, x0, 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, x0) gamma_armijo(f, grad_f, x0);
  13. elseif strcmp(mode, 'minimized') == 1
  14. gamma_f = @(f, grad_f, x0) gamma_minimized(f, grad_f, x0);
  15. else % mode == 'fixed'
  16. gamma_f = @(f, grad_f, x0) gamma_fixed(f, grad_f, x0);
  17. end
  18. x_vals = x0; % Store iterations
  19. f_vals = f(x0(1), x0(2));
  20. for k = 1:max_iter
  21. grad = grad_f(x0(1), x0(2));
  22. % Check for convergence
  23. if norm(grad) < tol
  24. break;
  25. end
  26. hess = hessian_f(x0(1), x0(2));
  27. mI = m * eye(size(hess));
  28. % Solve for search direction using Newton's step
  29. dk = - inv(hess + mI) * grad;
  30. % Calculate gamma
  31. gamma = gamma_f(f, grad_f, x0);
  32. x_next = x0 + gamma * dk'; % Update step
  33. f_next = f(x_next(1), x_next(2));
  34. x0 = x_next; % Update point
  35. x_vals = [x_vals; x_next]; % Store values
  36. f_vals = [f_vals; f_next]; % Store function values
  37. end
  38. end