Advertisement
OreganoHauch

Find minimum of unimodal function with golden cut

Dec 4th, 2023 (edited)
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.47 KB | None | 0 0
  1. function [x,fx] = plot_minimum(f,a,b,epsilon,use_ginput)
  2. X = linspace(a,b,500);
  3. hold('off')
  4. plot(X, f(X), 'b-')
  5. hold('on')
  6. axis("manual")
  7. if use_ginput
  8.     a_vector = ginput(1);
  9.     plot(a_vector(1),a_vector(2), 'xk')
  10.     b_vector = ginput(1);
  11.     plot(b_vector(1),b_vector(2), 'xk')
  12.     a = a_vector(1);
  13.     b = b_vector(1);
  14. else
  15.    a = -4;
  16.    b = 2;
  17. end
  18. fprintf('a = %.2f\nb = %.2f\n', a,b)
  19. if a > b
  20.     disp('Digga, der erste Punkt muss LINKS sein!!!')
  21. end
  22. [x,fx] = find_minimum(f,a,b,epsilon);
  23. plot(x,fx,'or')
  24. hold('off')
  25. end
  26.  
  27. function [x,fx] = find_minimum(f,a,b,epsilon)
  28.     c = (3-sqrt(5))/2;
  29.     xa = a + c*(b-a);
  30.     xb = b - c*(b-a);
  31.     not_first_time = false;
  32.     while abs(a-b) >= epsilon
  33.         if f(xa) < f(xb)
  34.             b = xb;
  35.             xb = xa;
  36.             xa = a + c*(b-a);
  37.         elseif f(xa) > f(xb)
  38.             a = xa;
  39.             xa = xb;
  40.             xb = b - c*(b-a);
  41.         end
  42.     fprintf('a = %f\nx_a = %f\nx_b = %f\nb = %f\n--------\n',a,xa,xb,b)
  43.    
  44.     hold('on')
  45.     if not_first_time
  46.         delete(a_plot)
  47.         delete(xa_plot)
  48.         delete(xb_plot)
  49.         delete(b_plot)
  50.     end
  51.     a_plot = plot(a,f(a),'mo');
  52.     xa_plot = plot(xa,f(xa), 'mo');
  53.     xb_plot = plot(xb,f(xb), 'mo');
  54.     b_plot = plot(b,f(b), 'mo');
  55.     not_first_time = true;
  56.  
  57.    
  58.     pause(1.5)
  59.    
  60.     end
  61. x = xa;
  62. fx = f(xa);
  63. end
  64.  
  65. f=@(x) 10+x.^2-10*cos(2*pi*x); a=-10; b=10; epsilon=1e-5; plot_minimum(f,a,b,epsilon,true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement