clc; close all; clear all;
syms x;
g = [1 2 3 4 5]
for i= 1:5
f=g(i)*exp(x)-1;
df=diff(f);
y = newtonraphson(x,f, df, 5, 0.001);
fprintf('%.4f', y);
end
function y = newtonraphson(x, f, df, n, x0)
rounding = 5*10^-(n+1);
for i=1:100
f0=vpa(subs(f,x,x0));
f0_der=vpa(subs(df,x,x0));
y=x0-f0/f0_der;
err=abs(y-x0);
if err<rounding
break;
end
x0=y;
end
y = y - rem(y,10^-n);
fprintf('The Root is : %f \n',y);
fprintf('No. of Iterations : %d\n',i);
end
I am learning to use newton raphson method to solve equations.
My function works when g is a single value, say 1 or x. This is without the for loop, for a basic equation.
I added the for loop as I wanted g to have a matrix/array input. Would appreciate the guidance. Thank you!