% Demo for 1-D section of Chapter 5
% solves minimzation problem 
%by various approaches
%First plot the function
clear
f = inline('x*x-2*x+2');
fv = vectorize(f);
X = -2:0.1:2;
F = fv(X);
plot(X,F)
title('Objective Function')
xlabel ('X')
ylabel ('F(x)')
%obtain initial guess for the unimodal region
xguess = input ('Enter the xlo,xhi guess as column vector')
tol = input ('Enter tolerance for solution')
%Apply the golden section search method
    tau = (sqrt(5)-1)/2.;
    a = xguess(1);
    b = xguess(2);
    x1 = a+(1-tau)*(b-a);
    f1= f(x1);
    x2 = a + tau*(b-a);
    f2 = f(x2);
    icount=0;
    while ((b-a)> tol)
       icount = icount+1;
       if (f1 > f2) 
          a = x1;
          x1 = x2;
          f1 = f2;
          x2 = a+tau*(b-a);
          f2 = f(x2);
       else
          b = x2;
          x2 = x1;
          f2 = f1;
          x1 = a+(1-tau)*(b-a);
          f1= f(x1);
       end
       [a,b]
    end
    disp ('results of golden section search')
    disp ('convergence after interation number')
    icount
    disp ('function minimum found at x = ')
    a
pause
    disp ('use library minimizer fminbnd')
    disp (' combo of golden search and parabolic interp')
    x1 = xguess(1);
    x2 = xguess(2);
    options = optimset('TolX',tol,'Display','iter')
    [xmin fmin]=fminbnd('x*x-2*x+2',x1,x2,options)
    pause
    %to check values of function near minimum
    disp('enter x values to evaluate function at test values')
    for i = 1:30
       xval = input ('input an x value')
       ftest = f(xval)
    end
pause

      
