Newton Raphson!but with multiple initial values :/

1 次查看(过去 30 天)
This works for one initial value. Now I want to do the exact thing but for 2 more initial values. Where they all are x0= [0.5,1.5,2.5]; and the outputs will be r = [r1 , r2 , r3]. Any help would be appreciated, thanks.
r1 = newtonr()
function[r]= newtonr
i = 0;
x0=0.5;
n = 5;
while i < 5
f = x0^4 - 9*x0^3+29*x0^2-39*x0+18;
df= 4*x0^3 - 27*x0^2 +58*x0 -39;
xnew= x0 - f/df;
i= i+1
x0=xnew;
disp(x0);
if i== 5
r= xnew;
disp('root is')
disp(x0)
break
end
end
end

采纳的回答

David Hill
David Hill 2020-5-5
i = 0;
x=[0.5,1.5,2.5];
n = 5;
f = @(x)x.^4 - 9*x.^3+29*x.^2-39*x+18;
df= @(x)4*x.^3 - 27*x.^2 +58*x -39;%functions should not be in loop
while i < 5
x= x - f(x)./df(x);
i= i+1
disp(x);
end
disp('roots are: ');
disp(x);

更多回答(1 个)

Michael Soskind
Michael Soskind 2020-5-5
编辑:Michael Soskind 2020-5-5
Hi Alex,
Edited: Please note, David Hill's answer is the one I recommend.
As a note:
To make calculations work on multiple values within an array, the operator should be preceded with a '.'
This is the case for multiplication, division, and raising to a power.
This is the main modification that David makes in his code, as well as implementing functions for the function and its derivative. This is in general better practice.

Community Treasure Hunt

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

Start Hunting!

Translated by