How can find the maximum of f(x) by updating initial guesses in a loop?

2 次查看(过去 30 天)
As homework a 'simple grid search' must be coded to find the maxima of f(x) = 2*ln(x)-2*x+5.
The simple grid search takes two initial guesses (xa, xb) and devides them over 5 intervals of equal lenght (xa , (xa+xb)*(1/4) , (xa+xb)*(2/4) , (xa+xb)*(3/4) , xb). Then the code checks for three consecutive intervals in which a maximum is, and takes the outer two points to be iterated again as new initial guesses, this results in more narrow intervals each iteration until a chosen accuracy is acquired.
My code can find the intervals in which a maximum is because i leave it no choice. However, it fails to update the new initial guesses correctly, i think because i dont know how to properly start at the beginnen of the loop again. This is my code:
clear all
xa = 0; %Initial guess xa < xb
xb = 10; %Important: f(xa) < max < f(xb)
iter = 10;
f = @(x) 2*log(x) - 2*x + 5;
for k = 1:iter
x1 = (xa) %Assuming a maximum is between xa and xb
x2 = (xa+xb)*1/4
x3 = (xa+xb)*2/4
x4 = (xa+xb)*3/4
x5 = (xb)
if (f(x1) < f(x2))
if (f(x2) < f(x3))
if (f(x3) < f(x4))
if (f(x4) < f(x5))
xa = x3;
xb = x5;
else
print('Choose better initial guesses')
end
else
xa = x2; %0.5
xb = x4; %1.5
end
else
xa = x1;
xb = x3;
end
else
print('Choose better initial guesses')
end
if abs((x4-x3)) < 0.001
break
end
end
fprintf('The maximum is %f\nNumber of iterations: %d\n',x3,k)

回答(2 个)

Divya Yerraguntla
Divya Yerraguntla 2020-3-31
Hi Loic,
I dont see any issue with the updation of initial guesses in your code.
The initial guesses keep updating until the 3rd iteration and then they saturate because your maxima is already found at 3rd iteration itself. So you could change the value of 'iter' variable to 3 and still be able to find maxima.
Hope it helps!

loic roure
loic roure 2020-4-2
编辑:loic roure 2020-4-2
The problem was that the 5 intervals, x1 to x5, do not linearly increase. This is explained wrong in Numerical Methods by C. Woodford, C. Phillips on page 171.
To have a linearly increasing grid, set:
x1 = xa + (xb - xa)*0/4
x2 = xa + (xb - xa)*1/4
x3 = xa + (xb - xa)*2/4
x4 = xa + (xb - xa)*3/4
x5 = xa + (xb - xa)*4/4

类别

Help CenterFile Exchange 中查找有关 Solver Outputs and Iterative Display 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by