matlabtype-conversiondiffderivativefunction-handle

How to convrt 1x1 sym to function/expression?


Below you can find implemented Newton method.

function y = NewtonRoot(Fun, DFun, Xest,Err, imax)
%Fun - function
%DFun- derivative of F
%Xest - initial estimate of solution
%Err - maximum error
%y - solution

%EXAMPLE: NewtonRoot(@(x)x^2-4,@(x)2*x,1.3, 0.001, 100)

for i= 1: imax
    Xi = Xest - feval(Fun,Xest)/feval(DFun,Xest);
    if abs((Xi-Xest)/Xest) < Err
        y = Xi;
        break
    end
    Xest= Xi;
end

if i== imax
    fprint('Solution was not obtained in %i iterations.\n', imax)
    y=('No answer');
end

It is working:

NewtonRoot(@(x)x^2-4,@(x)2*x,1.3, 0.001, 100)

but in the fact I want to calculate the derivative of a more complex function. Hence, I tried to use diff function but it isn't working... Could you please help me?

That's my tentative:

syms y(x) x
y=@(x)x^2-4
dy = diff(y,x)

NewtonRoot(y,@(x)diff(y,x),1.3, 0.001, 100)


Solution

  • You can use the matlabFunction function, that allows convert symbolic expression to function handle. Thus, for this example:

    syms y(x) x
    y=@(x)x^2-4;
    dy = diff(y,x);
    
    NewtonRoot(y, matlabFunction( diff(y,x)), 1.3, 0.001, 100)
    

    Which apparently works quite well.