For loop only once

5 次查看(过去 30 天)
a
a 2014-11-16
评论: a 2014-11-17
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])

采纳的回答

Geoff Hayes
Geoff Hayes 2014-11-16
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!
  1 个评论
a
a 2014-11-17
Wow amazing work!!! thank you very much!
I love you!!!!!!!!!!!!!!!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by