matlabanonymous-functionderivativefunction-handle

Derivative of anonymous functions without defining symbolic variables in Matlab


Consider the following code:

f = @(x) x.^2; 

Is it possible to get the derivative of the function handle f as another function handle, without defining a symbolic variable?


Solution

  • No, to obtain a derivative function you need to use the Symbolic toolbox.

    But you can get an approximation (finite difference approximation) by creating a function as follows:

    f = @(x) x.^2;
    d = 1e-6;
    df = @(x) (f(x+d)-f(x))/d;
    

    d here determines precision of the approximation. If you make it too small, you'll end up in the floating-point rounding error domain, so be careful!

    Testing:

    x = -2:0.01:2;
    max(abs(df(x) - 2*x))  % returns 1.0006e-06