symbolic derivative with constant output

2 ビュー (過去 30 日間)
Fabio Freschi
Fabio Freschi 2019 年 2 月 22 日
回答済み: Walter Roberson 2019 年 2 月 22 日
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 件のコメント
Fabio Freschi
Fabio Freschi 2019 年 2 月 22 日
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 2019 年 2 月 22 日
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

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2019 年 2 月 22 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeInterpolation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by