Let the future tell the truth and evaluate each one according to his work and accomplishments. The present is theirs; the future, for which I really worked, is mine. (Nikola Tesla)

12/06/2011

● Finding Maximum and Minimum by Golden-Section Search using MATLAB

This program implements the golden-section search algorithm. It locates the minimum or maximum of the function depending on the user’s preference, iterates until the relative error falls below a stooping criteria or exceeds an maximum number of iterations, return both the optimal x and f(x), minimizes the number of function evaluations.

r=(sqrt(5)-1)/2; %Golden Rate
disp('Number of max iteration')
maxiter=input('maxiter= ');
disp('Value of tolerance')
tol=input('Tol= ');
disp('For max enter "1", for min enter "0"')
x=input('minmax= ');
a=input('Lower bound= '); %Lower limit
b=input('Upper bound= '); %Upper limit
disp(' ')
disp('k x1 x2')

for k=1:maxiter
if (x==1) %Part that will find max
x1=a+r*(b-a); %First one of the points inside
x2=b-r*(b-a); %Second one of the points inside
fx1=-x1^4-2*x1^3-8*x1^2-5*x1; %Value of fx at first inside point
fx2=-x2^4-2*x2^3-8*x2^2-5*x2; %Value of fx at second inside point
if fx1>fx2 %Changing interval as [x2,b]
a=x2;
x2=x1;
x1=a+r*(b-a);
else
b=x1; %Changing interval as [a,x1]
x1=x2;
x2=b-r*(b-a);
end
fprintf ('%d %7.5f %7.5f\n', k,x1,x2)
%Stop if the error is below tolerance
if(abs((x1-x2))
end
else %Part that will find min
x1=a+r*(b-a);
x2=b-r*(b-a);
fx1=3+6*x1+5*x1^2+3*x1^3+4*x1^4;
fx2=3+6*x2+5*x2^2+3*x2^3+4*x2^4;
if fx1
a=x2; %Changing interval as [x2,b]
x2=x1;
x1=a+r*(b-a);
else
b=x1; %Changing interval as [a,x1]
x1=x2;
x2=b-r*(b-a);
end
fprintf ('%d %7.5f %7.5f\n', k,x1,x2)
if(abs((x1-x2))
end
end
end
disp(' ')
disp('Results')
disp('x1 x2 f(x1) f(x2)')
fprintf ('%7.5f %7.5f %7.5f %7.5f\n',x1,x2,fx1,fx2)



ShareThis