% 7.1 1D search for minimum

clear
format long

f=@(x) x.^4+3*x.^2-5*x+1;

x=-1:.01:2;
figure;plot(x,f(x));hold on;

a=-1;
b=2;
lambda=double((sqrt(5)-1)/2);% golden proportion, around 0.618

c=lambda*a+(1-lambda)*b;
d=(1-lambda)*a+lambda*b;

fc=f(c);
fd=f(d);

plot(c,fc,'kx',d,fd,'kx')

count=0; 
while abs(b-a)>1e-6 && count<100
    count=count+1;
    
    if fc<fd
        b=d;
        d=c;
        c=lambda*a+(1-lambda)*b;
        
        fc=f(c);
        fd=f(d);
        
        plot(c,fc,'kx');
    else % fc > fd
        a=c;
        c=d;
        d=(1-lambda)*a+lambda*b;
        
        fc=f(c);
        fd=f(d);
        
        plot(d,fd,'kx')
    end
end

% pick minimum
if fc<fd
    xmin=c;fmin=fc;
else
    xmin=d;fmin=fd;
end
[xmin fmin]
plot(xmin,fmin,'rx','MarkerSize',20)