Newton's Method Help

6 vues (au cours des 30 derniers jours)
Kaeden Beaty
Kaeden Beaty le 12 Fév 2021
Commenté : Alan Stevens le 12 Fév 2021
I have a code that works for Newton's method, but I am trying to make it into an algorithm that takes an imput from the interval [a, b] instead of x0. In other words I guess the initial point is calculated inside of the cody using x0=(a+b)/2. Another thing I would like to do is insert an if statement into the main loop that breaks out of the loop if the x is outside of [a, b]. This is the original that works, but uses an input of x0.
function x=mynewton(f,df,x0,tol,maxiter)
x=x0;
xold=x
for i=1:maxiter
x=x-f(x)/df(x)
err(1)=abs(x-xold)
xold=x
if err(1)<tol
break
end
end
And then this is what I tried to do but there is an error
function x=mynewton2(f,df,x0,tol,maxiter)
x=(a+b)/2;
xold=x
for i=1:maxiter
x=x-f(x)/df(x)
err(1)=abs(x-xold)
xold=x
if err(1)<tol
break
end
if x<a
break
end
if x>b
break
end
end
end
I am really sorry if this is a stupid question, I am just very new to MATLAB and am not the best with technology. Any help would be much appreciated!

Réponse acceptée

Alan Stevens
Alan Stevens le 12 Fév 2021
Assuming you make
x0 = [a, b];
before you pass it to the function, then replace
x = (a+b)/2;
by
x = (x0(1) + x0(2))/2;
within mynewton2.
  2 commentaires
Kaeden Beaty
Kaeden Beaty le 12 Fév 2021
ohh thank you so much! so x0(1) refers to the x value of x0. So if I wrote x0=[a,b,c] then x0(3) would refer to the value of c right?
Alan Stevens
Alan Stevens le 12 Fév 2021
Yes. (though x0(1) refers to the first value of x0).

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by