Why is the answer in my command window multiplying every time I press run??

조회 수: 1 (최근 30일)
Britney
Britney 2014년 10월 9일
댓글: Britney 2014년 10월 14일
So I got the correct code..I think but when I press run the answer first showed up as x2 and when I pressed run the answer showed up x4 on command window.
My function:
function x=my_newton(f,Df,x0,tol)
%f=@(x)(x.^3-cos(4*x));
%Df=@(x)((3*x^2)+(4*sin(4*x)));
x=x0;kmax=10; tol=0.5e-8;
for k=1:kmax
d=-f(x)/Df(x);
x=x+d;
disp([x d])
if abs(d)<tol, break
end
end
msg=sprintf('warning');
if k==kmax, disp(msg);
end
And in a separate script I run:
f=@(x)(x.^3-cos(4*x));
x=linspace(-3,7);
plot(x,f(x))
axis([-3 7 -5 10]);grid on
hold on
%--------------
f=@(x)(x.^3-cos(4*x));
Df=@(x)((3*x^2)+(4*sin(4*x)));
x=my_newton(f,Df,[-0.9],1e-8);
x=my_newton(f,Df,[-0.4],1e-8);
x=my_newton(f,Df,[0.4],1e-8);
I get correct answer in Command window but first the answer showed up in x2 and then when I pressed again run and it just multiplies....What is wrong?
  댓글 수: 6
Andrew Reibold
Andrew Reibold 2014년 10월 10일
definitely has to be related to clearing.
Britney
Britney 2014년 10월 14일
sorry I saw just now that you commented on my question. I figured out what was wrong. It was the disp() in my while loop. I just put a % in front of it and my code worked out fine.
Thank you for taking the time.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by