MATLAB: For loop help – Newton’s method

for loopiterationloopsMATLAB

Hi, I am trying to find the root/s of a polynomial using Newton's method, underneath is what I got till now. I wish to improve this code by somehow modifying the for loop to keep iterating until a fixed root is found i.e., the answer converges to a specified accuracy. Any ideas? Thanks !!
DP = 16;
DP_old = digits;
digits(DP);
DP_current = digits;
syms x
f_x = 2*x^5 - 6*x^4 -12*x^3 + 20*x^2 + 42*x + 18; % roots = [-1 -1 -1 3 3]
d_f_x = diff(f_x);
n = 77;
x_k = zeros(1, n);
for i = 1:n %keep looping until for example x_k(i+1) = -1
disp(i);
x_k(i+1) = x_k(i) - (subs(f_x, x_k(i))/subs(d_f_x, x_k(i)));
disp(vpa(x_k(i+1)));
end
root = round(min(x_k));
fprintf("root = %d\n\n", root);

Best Answer

I would avoid symbolic unless you need to.
f = [2,-6,-12,20,42,18];
df = polyder(f);
tol=1e-10;
error=1;
x=[-2,4];%initial root guesses
for i = 1:length(x)
while error>tol
a = x(i) - polyval(f,x(i))/polyval(df,x(i));
error=abs(a-x(i));
x(i)=a;
end
error=1;
end