MATLAB: For loop only once

for loop

Hi i want get root of equation.
but my script shows many same roots. i want show like function roots.
how can i do more?
clc
clear
pre_x1=0;
x2=[];
eps = 1e-9;
for n = -100:1:100
options = optimset('Display', 'off');
x1 = fzero('x^3 -6*x^2 + 11*x -6',n,options);
if (isnan(x1) == 0 && pre_x1 ~= x1)
% fprintf('guess = %5d, sol=%f10.n\n',n,x1);
if x1 == x1
pre_x1 = x1;
x2(end+1) = x1;
end
end
end
x2
roots([1 -6 11 -6])

Best Answer

You have the correct idea but have to remember that you cannot compare floating precision numbers using the equality (or negation of it). The
pre_x1 ~= x1
would be fine if both of these variables are integers but when it comes to floating-point numbers, you should use something more like
abs(pre_x1-x1)>eps
In the above, we consider the difference between the two numbers, and if they are greater than epsilon (note that eps is a built-in function) then the two are different. So using this will cut down on the number of duplicate roots.
Unfortunately, you can't assume that the roots will always be ordered so you will have to review the list of all found roots rather than just the previous one. So your code becomes
if ~isnan(x1)
% indicator as to whether a duplicated root has been found (true)
% or not (false)
dupRootFound = false;
% loop through all roots found so far
for k=1:length(x2)
if abs(x2(k)-x1)<eps
% a duplicated root has been found so exit
dupRootFound=true;
break;
end
end
if ~dupRootFound
% no duplicated root found so add it
x2 = [x2 x1];
end
end
Just replace your if block with the above and see what happens!
Related Question