MATLAB Answers

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

2 views (last 30 days)
loic roure
loic roure on 25 Mar 2020
Edited: loic roure on 2 Apr 2020
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)

  0 Comments

Sign in to comment.

Answers (2)

Divya Yerraguntla
Divya Yerraguntla on 31 Mar 2020
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!

  0 Comments

Sign in to comment.


loic roure
loic roure on 2 Apr 2020
Edited: loic roure on 2 Apr 2020
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

  0 Comments

Sign in to comment.


Translated by