For loop only once

조회 수: 2 (최근 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