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

3 visualizaciones (últimos 30 días)
Britney
Britney el 9 de Oct. de 2014
Comentada: Britney el 14 de Oct. de 2014
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 comentarios
Andrew Reibold
Andrew Reibold el 10 de Oct. de 2014
definitely has to be related to clearing.
Britney
Britney el 14 de Oct. de 2014
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.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by