Derivative of function handle

295 views (last 30 days)
Erez Dahan
Erez Dahan on 27 May 2018
Commented: Walter Roberson on 27 May 2018
Hello, I've seen a solution on here about how to calculate a derivative function of a function handle here. I would like an explanation of exactly what does this line do: f1 = eval(['@(x)' char(diff(f(x)))])
>> syms x
>> f = @(x) x + log(x)
f =
@(x)x+log(x)
>> f1 = eval(['@(x)' char(diff(f(x)))])
f1 =
@(x)1/x+1
>> f2 = eval(['@(x)' char(diff(f1(x)))])
f2 =
@(x)-1/x^2

Answers (1)

Rik
Rik on 27 May 2018
Let go through this step by step.
To take the derivative of a symbolic function, you have to create a function handle, which is done with the first two lines.
The diff function works in different ways depending on the input. It either takes the numeric difference (shortening the vector length by 1), or calculating the derivative of a function handle. The first syntax would be diff(f(3)), while the second would be diff(f(x)).
Because you want to use the result to convert it to a function handle (a symbolic function or anonymous function), you need to convert the result from diff to the displayed text. That is what the char is doing.
Now you have a problem: your code is saved as text. Luckily there's a function you should otherwise leave alone: eval. That function takes strings/char arrays as an input and returns the result as if that array had been typed as normal code. In this case you add the @(x) to retain the input possibilities.
You could try to be a smart guy and use f1=@(x) diff(f(x)); instead, but that doesn't work because of the first syntax of diff. This line of code first calculates f(x), and then does diff. As the input to diff is just a regular scalar, it calculates the numeric difference, which reduces the length of the input by 1, resulting in an empty output. If you put in a vector, the result would be even worse, as you would get a vector response, but not what you would expect.
Hope this helps.
  3 Comments
Rik
Rik on 27 May 2018
Thank you for the addition. I was already wondering if there really was no alternative to eval here. That did seem odd to me.
Walter Roberson
Walter Roberson on 27 May 2018
f1 = str2func['@(x)' char(diff(f(x)))])
However, char() of a symbolic expression is not necessarily MATLAB code. For example,
>> syms x y
>> char([x,y])
ans =
'matrix([[x, y]])'
Also, some of the routines in symbolic expressions mean something different than the MATLAB routines of the same name, or need to be converted like int() needs to be converted to integral() .
If you have a symbolic expression that you need to make into a function handle to apply to numeric arguments, then use matlabFunction()

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!