symbolic derivative with constant output

2 views (last 30 days)
Hi everyone,
I am working on a code requiring the definition of an anonymous function that is the derivative of another anonymous function specified at runtime. The use of matlabFunction is straightforward in most cases, and the resulting anonymous function can be used as the original function.
>> syms t
>> x = @(t)sin(t);
>> dxdt = matlabFunction(diff(x(t)))
dxdt =
function_handle with value:
@(t)cos(t)
>> dxdt(10)
ans =
-0.8391
However, it could happen that the original anonimous function can be linear or constant. In this case matlabFunction creates an output that does not accepts inputs:
>> syms t
>> x = @(t)10*t;
>> dxdt = matlabFunction(diff(x(t)))
dxdt =
function_handle with value:
@()1.0e1
>> dxdt(10)
Error using symengine>@()1.0e1
Too many input arguments.
How can I define the derivative of an anonymous function such that the output in the last case is usable with one input for any input? In the previous case I would like to have something like:
dxdt = @(t)10;
Thanks in advance
Fabio
  3 Comments
Fabio Freschi
Fabio Freschi on 22 Feb 2019
Because the code is rather general and the derivative is used later in the algorithm.
Since I don't have the control of the input function x(t), I would like to have a comprehensive implementation that covers also the latter case
madhan ravi
madhan ravi on 22 Feb 2019
you can like use nargin() to check the number of the inputs in a function and can create an if condition to process your data further according to the number of inputs

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 22 Feb 2019
matlabFunction(diff(x(t),t), 'vars', t)
The result would permit one input argument. However, it would return a scalar output no matter what the size of the input. So what you can do is
temp = diff(x(t),t);
if isempty(symvar(temp))
tempdxdt = matlabFunction(temp, 'vars', t); %when the value is a constant, the generated function returns a scalar no matter what size of t is
dxdt = @(t) ones(size(t)) * tempdxdt(t);
else
dxdt = matlabFunction(temp, 'vars', t);
end

More Answers (0)

Categories

Find more on Interpolation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!