Search code examples
matlabfunctionnumerical-methodsnewtons-method

Need A Newton Raphson matlab function


i have a polynomial f(x)= x^3-a and i need its matlab function with parameters

function [x,err]=cubic1(a,xinit,eps) where xinit: Initial approximation eps: iterations are performed until approximate error is less than this number x: Root approximations of the function, and it is an array. relerr: Approximate errors corresponding to the iterations and it is an array.

do you have any idea ?


Solution

  • function [x,err] = cubic1(f,df_dx,x0,eps)
       err = Inf;
       x = x0;
       while abs(err) > eps
          x_old = x;
          x = x_old - f(x_old)./df_dx(x_old);
          err = x - x_old;
       end
    

    To call the cubic1 function,

    a = 1; % you can change a
    f = @(x)(x.^3-a);
    df_dx = @(x)(3*x.^2);
    x0 = 1;
    eps = 1e-7;
    [x,err] = cubic1(@f,@df_dx,x0,eps);