How to implement a derivative of a symbolic function by a 'symfun' in Matlab?

◇◆丶佛笑我妖孽 提交于 2019-11-29 14:34:40

In newer versions of Matlab (I'm using R2014b) the error message is clearer:

Error using sym/diff (line 26) All arguments, except for the first one, must not be symbolic functions.

So, it looks like sym/diff cannot take a derivative with respect to what the documentation calls an abstract or arbitrary symfun, i.e., one without a definition. This limitation is not explicitly mentioned in the documentation, but the various input patterns allude to it.


Workaround 1: Simple functions, independent variable t only appears in differentiated symfun

I haven't found any workaround that is particularly elegant. If t only appears in your variable of interest (here x(t)), and not on its own or in other abstract symbolic functions, you can differentiate with respect to time t and then cancel out the extra terms. For example:

syms t x(t) y(t) z
f1 = x^2+5;
f2 = x^2+z^2+5;
f3 = x^2+y^2+z^2+5+t;
dxdt = diff(x,t);
df1 = diff(f1,t)/dxdt
df2 = diff(f2,t)/dxdt
df3 = diff(f3,t)/dxdt

which returns the requisite 2*x(t) for the first two cases, but not the third, for the reasons stated above. You may need to apply simplify in some cases to fully divide out the D(x)(t) terms.


Workaround 2: More robust, but more complicated method

Using subs multiple times, you can replace the symbolic function in question with a standard symbolic variable, differentiate, and swap it back. For example:

syms t x(t) y(t) z
f3 = x^2+y^2+z^2+5+t;
xx = sym('x');
df3 = subs(diff(subs(f3,x,xx),xx),xx,x)

which also returns 2*x(t) for the third case above. But I think this is kind of an ugly hack.

It is kind of ridiculous that Matlab can't do this – Mathematica has no such problem. It appears that MuPAD itself has this limitation. You might consider filing a feature request with The MathWorks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!