2

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?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Msh
  • 192
  • 2
  • 7

1 Answers1

6

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
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • 3
    Or even better, use higher order schemes, or at least using a central difference `@(x) (f(x+d)-f(x-d))/(2*d)` - allowing you increased accuracy for the same `d`. This is the correct approach though – Wolfie Feb 08 '19 at 11:26