Rom
Rom

Reputation: 225

Multiple anonymous function MATLAB

My goal is to compute the derivative of a function and use this result as another function. Clearly, it means :

f = @(x) (x-1)*(x-2);      %A simple function
derivative = jacobian(f,x) %MATLAB output : "2*x - 3"
df = @(x) derivative       %= @(x) 2*x - 3
df(2)                      %= "2*x -3" instead of 2*2 - 3

How can I do such a thing ? I tried syms x but it doesn't help.

Upvotes: 1

Views: 69

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You want matlabFunction:

g = matlabFunction(f) converts the symbolic expression or function f to a MATLAB function with handle g.

In your example:

>> syms x
>> f = @(x) (x-1)*(x-2);
>> derivative = jacobian(f,x);
>> df = matlabFunction(derivative)
df =
  function_handle with value:
    @(x)x.*2.0-3.0
>> df(2)
ans =
     1

Upvotes: 3

Related Questions