THMMY's "Optimization Techniques" course assignments.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

plotContour.m 1.3 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. function plotContour(fun, x_lim, y_lim, size, plot_title, filename)
  2. % plot the contour of a function
  3. % fun: The function to plot
  4. % x_lim: The range for x axis. ex: [-2, 2]
  5. % y_lim: The range for y axis. ex: [0, 2]
  6. % size: The number of points for each axis
  7. % plot_title: The latex title for the plot
  8. %
  9. global image_width,
  10. global image_height;
  11. % Generate a grid for x and y
  12. x_space = linspace(x_lim(1), x_lim(2), size);
  13. y_space = linspace(y_lim(1), y_lim(2), size);
  14. [X, Y] = meshgrid(x_space, y_space);
  15. % Evaluate the function on the grid
  16. for i = 1:size
  17. for j = 1:size
  18. % Pass each [x1; x2] as input to fun
  19. Z(i, j) = fun([X(i, j); Y(i, j)]);
  20. end
  21. end
  22. % Contour
  23. figure('Name', 'Contours of f(x1,x2)', 'NumberTitle', 'off');
  24. set(gcf, 'Position', [100, 100, image_width, image_height]); % Set the figure size
  25. contour(X, Y, Z);
  26. % Customize the plot
  27. xlabel('x1'); % Label for x-axis
  28. ylabel('x2'); % Label for y-axis
  29. title(plot_title, 'Interpreter', 'latex', 'FontSize', 16); % Title of the plot
  30. colorbar;
  31. % save the figure
  32. if strcmp(filename, '') == 0
  33. print(gcf, filename, '-dpng', '-r300');
  34. end
  35. end