Create an anonymous function after Symbolic differentiation

4 ビュー (過去 30 日間)
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 13 日
コメント済み: Walter Roberson 2018 年 4 月 13 日
I want to differentiate a function f and the calculate the derivative of f at value of x. How can I do that? for example:
syms x
f=@(x) x^3+3*x+1;
g=diff(f(x))
Preferably I would like to create a function handle of the derivative and then calculate the derivative at x.

採用された回答

Sean de Wolski
Sean de Wolski 2013 年 5 月 13 日
Almost there!
gfun = matlabFunction(g)
g(2)
  4 件のコメント
Troy
Troy 2018 年 4 月 13 日
But what if the original function is just x? For example:
syms x
f=@(x) x;
g = matlabFunction(diff(f(x))
gives the result g = @()1.0 which is not a useable function. How to resolve?
Walter Roberson
Walter Roberson 2018 年 4 月 13 日
df = diff(f(x));
if isempty(symvar(df))
g = str2func(['@(x) repmat(', char(df), ', size(x))'])
else
g = matlabFunction(df);
end
Note: this will fail in some cases where the derivative just happens to be an expression involving a syntax that differs between MATLAB and the Symbolic Toolbox. For example,
f(x) = int(coth(cos(x)),x,1,5)*x
The int() part is actually a constant independent of the *x it is being muliplied by, so diff(f(x)) should be just int(coth(cos(x)),x,1,5), but if you emit that into the function handle you will fail when the handle is executed.
The situation could probably be improved by using
g = str2func(['@(x) repmat(', char(vpa(df)), ', size(x))'])
which will still lead to some failures, just perhaps fewer of them.

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

その他の回答 (1 件)

Iman Ansari
Iman Ansari 2013 年 5 月 13 日
Hi.
syms x
f=@(x) x^3+3*x+1;
g=diff(f(x))
h=@(y) subs(g,y)
  2 件のコメント
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 13 日
Thank you! But then if I ask for g(2) then I get this error:
Error using mupadmex
Error in MuPAD command: Index exceeds matrix dimensions.
Error in sym/subsref (line 1389)
B = mupadmex('symobj::subsref',A.s,inds{:});
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 5 月 13 日
with h(2) it works... thank you!

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by