0

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 ?

lennon310
  • 12,503
  • 11
  • 43
  • 61
Jeam
  • 31
  • 1
  • 4
  • 3
    This question needs a lot of work to be viable. You need to: (1) show that you understand what you're trying to do. (2) show us what you have tried and why you think it is failing. (3) formulate a real question. – carlosdc Nov 25 '13 at 00:17

2 Answers2

0
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);
lennon310
  • 12,503
  • 11
  • 43
  • 61
  • Here what is named cubic1 should be named newtonraphson, and the second code block should be wrapped in the actual cubic1 procedure that hast a signature as asked for. – Lutz Lehmann Dec 13 '13 at 10:55
  • Thank you LutzL. I just used the function name that Jeam provided. And cubic1 can be used to solve any given function once you also calculate df_dx. – lennon310 Dec 13 '13 at 12:30
  • Yes, of course, but cubic1(a,xinit,eps), as the name says, is intended to compute the cube root of a starting with xinit to within a precision of eps. So from your bottom part of the code, one would take the definitions of f, df_dx and the call `newton(@f,@df_dx,xinit,eps);` and put this as the body of the cubic1 function. – Lutz Lehmann Dec 13 '13 at 12:43
  • I'm sorry but I still don't quite catch up with your second opinion. Would you mind adding your function below as a supplementary? Thanks – lennon310 Dec 13 '13 at 14:55
0

Supplementary about the renaming of functions in lennon310's solution

file cubic1.m

function [x,err] = cubic1(a,xinit,eps)
    f = @(x)(x.^3-a);
    df_dx = @(x)(3*x.^2);
    [x,err] = newton_root(@f,@df_dx,xinit,eps);
end

function [x,err] = newton_root(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
end

One gets faster convergence with the Newton method for f(x)=x^2-a/x,

file cubic2.m

function [x,err] = cubic2(a,xinit,eps)
    err = Inf;
    x = xinit;
    while abs(err) > eps
        x3=x.^3;
        x_new = x*(x3+3*a)/(3*x3+a);
        err = x_new - x;
        x=x_new
    end
end
Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51