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

后端 未结 1 930
故里飘歌
故里飘歌 2020-12-21 05:17

Here is my Matlab program:

syms x(t) t;
f = x^2 + 5;

And the result of f:

f(t) = x(t)^2 + 5

1条回答
  •  囚心锁ツ
    2020-12-21 05:29

    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.

    0 讨论(0)
提交回复
热议问题