% cs3113f06HW05.m
% Script to call the user-defined function GoldenSectionF.m 
% that uses the golden search method to find a minimum of a 
% given function within a specified interval.
% K. Ming Leung, Nov. 6, 2008

clear all; format long;

% Define an anonymous function for the function to be minimized:
fcn = @ (x,a) 0.5 - x.*exp(-x.*x);

xminExact = 1/sqrt(2);      % exact location of the minimum
fvalExact = fcn(xminExact); % exact value of function at the min.
a = 0; b = 2;               % interval where min. is located 
tol = 1e-4;                 % tolerance should be < sqrt(eps)

% call function to perform a golden search to locate min:
% xmin = location of the min.
% fval = function value at the min.
[xmin,fval] = GoldenSectionF(fcn,a,b,tol)

% Instead of defining an anonymous function for the function 
% to be minimized, one can define a function file for it.
% This is more convenient if the function requires more than 
% a single programming line to compute.
% In that case take out the line
% fcn = @ (x,a) 0.5 - x.*exp(-x.*x);
% and replace the line
% [xmin,fval] = GoldenSectionF(fcn,a,b,tol)
% by
% [xmin,fval] = GoldenSectionF(@fcnFile,a,b,tol)
% assuming that the function file name is called fcnFile.

disp('Exact min and min. function values: ');
disp([xminExact,fvalExact]);

