function [xmin,fval] = GoldenSectionF(fcn,a,b,tol,varargin)
% GoldenSectionF.m
% Function implementing the golden section minimization of a scalar
% function of a single variable.
% The function must have a minimum in interval [a,b].
% tol is the tolerance.
% p can be used to pass parameters into the function fcn.
% K. Ming Leung. 05/06/03

tau = 0.5*(sqrt(5)-1); tau1 = 1-tau;
L = b-a;
x1 = a + tau1*L;
f1 = feval(fcn,x1,varargin);
x2 = a + tau*L;
f2 = feval(fcn,x2,varargin);

while ((b-a)>tol)
if (f1>f2)
a = x1;
x1 = x2;
f1 = f2;
x2 = tau1*a + tau*b;
f2 = feval(fcn,x2,varargin);
else
b = x2;
x2 = x1;
f2 = f1;
x1 = tau*a + tau1*b;
f1 = feval(fcn,x1,varargin);
end
end
xmin = x1;
fval = f1;