function exempel7_5GylleneSnittet()
close all
format short
f = @(x) cos(x)+x.^2-0.4*x;
referenceSolution = fminbnd(f,0,1) %builtIn matlab function for computing argmin_x f(x)

iter =8;
[a, b] = goldenSectionSearch(0,1,iter,f);
disp('GylleneSnittet')
disp('    a(k)      b(k)    f((a(k)+b(k))/2)')
disp([ a' b' f((a+b)'/2)])

end

function [a,b] = goldenSectionSearch(a,b,iter,f)
% Run #iter number of iterations

%%Algorithm initialization part
tau = (sqrt(5)-1)/2;
a(1)=a; b(1)=b;
Delta = b(1)-a(1);    
x(1)=a(1)+(1-tau)*Delta; fx = f(x(1));
y(1)=a(1)+tau*Delta; fy = f(y(1));

hold on
%% only for visualization
z = linspace(a(1),b(1));
plot(z,f(z))
height = 0.85; plotPoints(a(1), b(1), x(1), y(1), height,1); %

%% Algorithm iteration part

for k=2:iter
        
    %% The algorithm
    Delta = tau*Delta;

    if(fx<fy)
        h1 = plot([x(k-1)], [f(x(k-1))], 'ro', 'linewidth',2);
        h2 = plot([y(k-1)], [f(y(k-1))], 'bo', 'linewidth',2);
        % f(y(k-1))> f(x(k-1)) so contnue minimization over [xL, y(k-1)]
        a(k) = a(k-1); 
        b(k) = y(k-1);
        y(k) = x(k-1); fy = fx; %reuse old function evaluation rather than recomputing it
        x(k) = a(k)+(1-tau)*Delta; fx=f(x(k));
    else 
        % f(y(k-1)) <=f(x(k-1)), so contnue minimization over [x(k-1), xR]
        h2= plot([x(k-1)], [f(x(k-1))], 'bo', 'linewidth',2);
        h1= plot([y(k-1)], [f(y(k-1))], 'ro', 'linewidth',2);
            
        b(k) = b(k-1); 
        a(k) = x(k-1);
        x(k) = y(k-1); fx=fy; % reuse old function evaluation 
        y(k) = a(k)+tau*Delta; fy=f(y(k));
    end
    
    
    
    pause()
    %% Only used for visualization
    height = height-0.03; %only used for visualization
    plotPoints(a(k), b(k), x(k), y(k), height,k);
    pause()
    delete(h1)
    delete(h2)
end
    

end

function plotPoints(a,b,x,y,h,k)
%% Only for visualization
    figure(1)        
    
    text(a, h, ['a_', num2str(k-1)],'fontsize',13);
    text(x, h, ['x_', num2str(k-1)],'fontsize',13);
    text(b, h, ['b_', num2str(k-1)],'fontsize',13);
    text(y, h, ['y_', num2str(k-1)],'fontsize',13);
    gray = [0.4 0.4 0.4];
    patch([a b b a],[0.91 0.91 1.2 1.2],gray, 'FaceAlpha',0.25,'EdgeColor','none')
    axis([-0.05 1.05 h 1.2])
end
