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

1 次查看(过去 30 天)
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 个评论
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