Golden Section algorithm only iterating once?

Hi, I'm new to matlab and I'm having trouble with my code which uses the golden section method to calculate a maximum. I'm pretty sure it has something to do with the for loop, because the algorithm only seems to iterate once, but I'm not sure. Any help would be appreciated. Thanks!
function [xopt] = gss(xl,xu,N)
r=(-1+sqrt(5))/2;
d=r*(xu-xl);
x1=xl+d;
x2=xu-d;
f1=f(x1);
f2=f(x2);
for i=1:N
if f1>f2
xl=x2;
x2=x1;
x1=xl+d;
f2=f1;
f1=f(x1);
else
xu=x1;
x1=x2;
x2=xu-d;
f1=f2;
f2=f(x2);
end
if f1>f2
xopt=x1;
end
if f1<f2
xopt=x2;
end
end
end
function fout = f(x)
fout=-0.1*(x^2)-exp(-x);
end

Respuestas (1)

Jan
Jan el 19 de Mzo. de 2016

0 votos

Use the debugger to see, what is going on: Set a breakpoint in the first line and step through the code line by line.
You will find out, that the loop runs N times as expected. But d does not change its value. Then you can expect that the calculated points are hopping back and forth.
Note: Using x1 and xl is a confusing idea. Hard to read...

1 comentario

Image Analyst
Image Analyst el 19 de Mzo. de 2016
I agree. Call them xLeft and xRight, or leftX and rightX, or xLower and xUpper, or something that is readable.

Iniciar sesión para comentar.

Categorías

Más información sobre Startup and Shutdown en Centro de ayuda y File Exchange.

Preguntada:

el 18 de Mzo. de 2016

Comentada:

el 19 de Mzo. de 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by