symbolic derivative with constant output
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Fabio Freschi
il 22 Feb 2019
Risposto: Walter Roberson
il 22 Feb 2019
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 Commenti
madhan ravi
il 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
Risposta accettata
Walter Roberson
il 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
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Interpolation in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!