1
votes

I have the below matlab code for newton raphson method.

a=1;b=4;c=-2;d=0;h=0.5;t=1;
x0 = -0.5+2i;
i = 1;
N = 100;                %maximum number of iterations
tol = 1e-4;         %precision required

syms x
p = @(x) x^2+a*x+b-c*exp(-x*h)-d*exp(-x*t);
f = @(x) a*x+b-lambertw(a*x+b-p*exp(a*x+b)); %function we are solving
df = diff(f);           %differential of f(x)

while i <= N
    numf = subs(f,x,x0); %// Numerator - Substitute f(x) for f(y)
    denf = subs(df,x,x0); 
    x = x0-double(numf)/double(denf);     %Newton-Raphson method 
    if (abs(x - x0)/abs(x))>tol     %stopping criterion 
    fprintf('Solution is %f \n', double(x))
    return
end
i = i + 1;
x0 = x;             %update p0
end
fprintf('Solution did not coverge within %d iterations at a required precision of %d \n', N, error)     %error for non-convergence within N iterations

When I ran it it gives the errors below:

  1. Error using mupadmex Error in MuPAD command: DOUBLE cannot convert the input expression into a double array.
  2. Error using diff Function 'diff' is not supported for class 'function_handle'. Error in line 10 diff = diff(f);
    %differential of f(x)

I don't know how to fix these errors. Help is truly appreciated.

1
Raplace 10 string on df = diff(f(x)); and will be examined with the last line. - user4651282
Thanks. It worked for second error but first error is still remaining. - user3563283
That's strange. What is your version of matlab and show a modified version of the code. My shows:Solution is 0.043026 - user4651282
Yes, you are right. Earlier I was using Matlab version 2013a in which the second error was still there but later I used 2014a in which it works perfectly with the same solution. No error. Thanks. - user3563283
But with this much precision the actual answer should be -0.07906+2.206i after third iteration which is not coming. How to display the iteration no? - user3563283

1 Answers

0
votes

Before the loop initialize x. Otherwise you would try to start the descend without an initial guess. The Newton method is a local method, so you need to choose the region, where you suspect the local minimum you want to converge to.

Then get rid of the double statement. As the error tells you double(x) is a function defined in muPad, which is not exactly matlab, but this little sub-program. Basically you can't use this function.

Use f(x), since you already have a function handle for that. And for df you can use subs(df,x) each iteration. This will replace the x in df with the x you give it in subs,.. make it double automatically by substitution.

Hints for use:

f = @(x) x^2
syms a
df = diff(f(a)) = 2*a
numeric_value1 = f(3) = 9.0
numeric_value2 = subs(df,3) = 6.0

The values are double, withou explicit declaration.