I thought I got the interval search AND the golden selection, here's my code. Can someone tell me where I went wrong? The code gives the same answer for two different functions with two different minima.
clear all
clc
errx = 0.001;
errf = 0.001;
xstart = -25;
fn = 'hw1f'; % The function name
grc=double((sqrt(5)-1)/2); %golden rule constant
%-----------------------------------------------
%interval search start
i=1;
x(1)=xstart;
x(2)=x(1)+2;
while feval(fn,x(i))>feval(fn,x(i+1))
i=i+1;
x(i+1)=x(i)+2;
end
b=x(i+1);
i=1;
x(1)=xstart;
x(2)=x(1)-2;
while feval(fn,x(i))>feval(fn,x(i+1))
i=i+1;
x(i+1)=x(i)-2;
end
a=x(i+1);
%interval search end
%------------------------------------------------
%Golden Selection Start
i=1;
x1=a+grc*(b-a);
x2=b-grc*(b-a);
while abs(x1-x2)>errx && abs(feval(fn,x1)-feval(fn,x2))>errf %termination check
if feval(fn,x1)>=feval(fn,x2)
b=x1;
x1=x2;
x2=b-grc*(b-a);
else
a=x2;
x2=x1;
x1=a+grc*(b-a);
end
i=i+1;
end
xmin=x2
fmin=feval(fn,x2)
iter=i
