THMMY's "Optimization Techniques" course assignments.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

86 lines
2.3 KiB

  1. function [] = iterations_over_lambda(method)
  2. % Calculate and plot iteration needed for different lambda values.
  3. %
  4. % method: the minimum calculation method
  5. % * bisections
  6. % * golden_section
  7. % * fibonacci
  8. % * bisection_der
  9. % return:
  10. % none
  11. %
  12. % Load the functions and interval
  13. GivenEnv;
  14. fig_dir = 'figures';
  15. if ~exist(fig_dir, 'dir')
  16. mkdir(fig_dir);
  17. end
  18. % Setup
  19. % ========================
  20. %
  21. % We need to test against the same lambda values for all the methods in
  22. % order to compare them. And since epsilon (which is related to lambda)
  23. % was given for the bisection method, we base our calculations to that.
  24. %
  25. %
  26. % epsilon: e = 0.001
  27. % lambda: l > 2e =>
  28. % lambda_min: 0.0021
  29. % lambda_max: 0.1
  30. % N: 50 points (50 lambda values)
  31. N = 50;
  32. epsilon = 0.001;
  33. lambda_min = 0.0021;
  34. lambda_max = 0.1;
  35. lambda = linspace(lambda_min, lambda_max, N);
  36. k = zeros(1, N); % preallocate k
  37. n = zeros(1, N); % preallocate n
  38. %
  39. % Call the minimum calculation method for each lambda value for each
  40. % function and keep the number of iterations needed.
  41. % Then plot and save the # of iterations k(lambda) for each function.
  42. %
  43. % note: In order to use the same method call for all methods, we force a
  44. % common interface for minimum method functions. Thus some arguments
  45. % will not be needed for some methods (epsilon is not needed for
  46. % bisection _der for example).
  47. %
  48. figure('Name', "iterations_over_lambda_" + char(method), 'NumberTitle', 'off');
  49. set(gcf, 'Position', [100, 100, 1280, 600]); % Set the figure size to HD
  50. disp(" ");
  51. for i = 1:length(funs)
  52. for j = N:-1:1
  53. [a, b, k(j), n(j)] = method(funs(i), a_0, b_0, epsilon, lambda(j));
  54. end
  55. fprintf('%20s(%34s ): [a, b]= [%f, %f], iters(min, max)= (%d, %d), calls(min, max)= (%d, %d)\n', ...
  56. char(method), char(funs(i)), a(end), b(end), k(N), k(1), n(N), n(1) );
  57. subplot(1, length(funs), i);
  58. plot(lambda, n, '-b', 'LineWidth', 1.0);
  59. title(titles(i), 'Interpreter', 'latex', 'FontSize', 16);
  60. xlabel('lambda');
  61. ylabel("Calls of f" + i);
  62. end
  63. %
  64. % Print and save the figures
  65. %
  66. %fig_epsc = fullfile(fig_dir, "iter_over_lambda_" + char(method) + ".epsc");
  67. fig_png = fullfile(fig_dir, "iter_over_lambda_" + char(method) + ".png");
  68. %print(gcf, fig_epsc, '-depsc', '-r300');
  69. print(gcf, fig_png, '-dpng', '-r300');
  70. close(gcf);