How can I implement a symbolic function derivative using "symfun" in Matlab?

Here is my Matlab program:

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

      

And the result f

:

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

      

Both f

and x

have a class symfun

in Matlab. I want to get a df / dx result that is 2*x(t)

. I tried this in Matlab:

diff(f, x);

      

and got the following errors:

Error using mupadmex
Error in MuPAD command: The variable is
invalid. [stdlib::diff]
Error in sym/diff (line 57)
    R = mupadmex('symobj::diff', S.s, x.s,
    int2str(n));

      

How can I get df / dx in Matlab?

+3


source to share


1 answer


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

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

So it looks like it sym/diff

cannot take derivative with respect to what the documentation calls abstract or arbitrary symfun

, i.e. without definition. This limitation is not explicitly mentioned in the documentation, but various input templates refer to it.


Workaround 1 : simple functions, independent variable t

only appears in differentiated symfun

I have not found a workaround that is particularly elegant. If t

only appears in the variable of interest (here x(t)

) and not on its own or in other abstract symbolic functions, you can differentiate by timing t

and then undo additional 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 required one 2*x(t)

for the first two cases, but not the third, for the reasons stated above. In some cases, you may need to apply simplify

to completely separate the terms D(x)(t)

.


Workaround 2 : a more reliable but more complex method

Using subs

multiple times, you can replace a symbolic function 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's ironic that Matlab can't do this - Mathematica doesn't have such a problem. It looks like MuPAD has this limitation. You can consider submitting a function request using MathWorks.

+5


source







All Articles