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

3 Ansichten (letzte 30 Tage)
Britney
Britney am 9 Okt. 2014
Kommentiert: Britney am 14 Okt. 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 Kommentare
Britney
Britney am 14 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by