Page 297 - MATLAB an introduction with applications
P. 297
282 ——— MATLAB: An Introduction with Applications
x2 = x1 + h; f2 = feval(func,x2);
if f2 > f1
h = –h;
x2 = x1 + h; f2 = feval(func,x2);
if f2 > f1
a = x2; b = x1 – h; return
end
end
% Search loop
for i = 1:100
h = c*h;
x3 = x2 + h; f3 = feval(func,x3);
if f3 > f2
a = x1; b = x3; return
end
x1 = x2; f1 = f2; x2 = x3; f2 = f3;
end
error(‘Failed to find minimum’)
function [xMin,fMin] = goldSearch(func,a,b,tol)
% Golden section search method
% func = function that returns f(x)
% a, b = limits of the interval for the minimum
% tol = error tol = 1.0e–6
% fMin = min of f(x)
% xMin = x at min point
if nargin < 4; tol = 1.0e–6; end
nIter = ceil(–2.078087*log(tol/abs(b–a)));
R = 0.618033989;
C = 1.0 – R;
x1 = R*a + C*b;
x2 = C*a + R*b;
f1 = feval(func,x1);
f2 = feval(func,x2);
for i =1:nIter
if f1 > f2
a = x1; x1 = x2; f1 = f2;
x2 = C*a + R*b;
f2 = feval(func,x2);
else
b = x2; x2 = x1; f2 = f1;
x1 = R*a + C*b;