How to count after how many iterations my program reached min/max of unimodal function

2 views (last 30 days)
So my task is to check after how many iterations my program will reach the local min/max of the given unimodal function. I've already created the algorithm which finds local min/max of my function but now I have struggle with creating a loop that will check after how many iterations it reached the min/max.
%3 Equal Distances Method
%method for finding a local maximum/minimum of a unimodal function
%y(x) = @(x) x/(1.2 - sin(2x))
%maximum = 4.08 at 0,8468
x = -1:1;
f = @(x) (x/(1.2 - 2.*(sin(x).*cos(x))));
hold on
figure(1)
plot(x,f(x))
a = -1;
b = 1;
d = 1./3 .* (b-a);
x1= a + d;
x2= b - d;
plot(a,f(a), '*g')
plot(b,f(b), '*r')
plot(x1,f(x1), '*m')
plot(x2,f(x2), '*b')
hold off
figure(2)
plot(x,f(x), 'k')
hold on
i=0;
while (a ~= 0.846:0.847)
f(x2)
f(x1)
if (f(x2) > f(x1))
i=i+1;
a = x1;
%b=b;
d = 1./3 .* (b-a);
x1= a + d;
x2= b - d;
else
if (f(x1) > f(x2))
i=i+1;
b = x2;
%a=a;
d = 1./3 .* (b-a);
x1= a + d;
x2= b - d;
else
end
end
plot(a,f(a), '*g')
plot(b,f(b), '*r')
end
hold off
display(a)
display(f(a))
display(b)
display(f(b))
display(i)
Here's my code with one of many attemps to create while loop which ended as infinite loop.

Answers (2)

Image Analyst
Image Analyst on 26 Oct 2015
You need to learn how to use the debugger to step on each line of code one at a time and find out why your loop is not exiting.
Also,
while (a ~= 0.846:0.847)
is not valid criteria.
In the meantime, it's essential if you use while loops to use a failsafe so that you don't get infinite loops. Usually the failsafe is just a loop counter, though it can be elapsed time. Pick a time or number of loops that you know it should never exceed, and test for that:
maxIterations = 1000000
while loopCounter < maxIterations && (a <= 0.846) || (a > 0.847)
% Code
loopCounter = loopCounter + 1;
end
I'm not sure what your criteria on the badly-named a are, so you need to take a look at that, but I know a ~= 0.846:0.847 is not what you want. If you want a to range from .846 to .847, then you should use a "for" loop.

Thorsten
Thorsten on 26 Oct 2015
Edited: Thorsten on 26 Oct 2015
You have to change the while expression, because a will never become exactly 0.846
while abs(a - 0.846) > 1e-3
and use point-wise division ./ in f (in order to plot the function properly)
f = @(x) (x./(1.2 - 2.*(sin(x).*cos(x))));
Note that you can simplify the body of your while loop by putting only the different parts of the code in the if/else clauses
while abs(a - 0.846) > 1e-3
f(x2)
f(x1)
abs(a - 0.846)
if f(x2) > f(x1)
a = x1;
elseif f(x1) > f(x2)
b = x2;
end
i = i+1;
d = 1./3 .* (b-a);
x1= a + d;
x2= b - d;
plot(a,f(a), '*g')
plot(b,f(b), '*r')
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!