I'm trying to compute the derivative of this function with respect to $\theta$ (i.e., $\frac{dv}{d\theta}$):
$$ v(t) = m_2 a_1 a_2 \dot{\phi}(t)\dot{\theta}(t) \cos(\theta(t)-\phi(t)) $$
I thought the answer was:
$$ \frac{dv}{d\theta} = -m_2 a_1 a_2 \dot{\phi}(t)\dot{\theta}(t) \sin(\theta(t)-\phi(t)) $$
But Matlab yields zero using this script:
clear variables
clc
syms t a1 a2 m2 th(t) p(t)
f = m2*a1*a2*diff(p,t)*diff(th,t)*cos(th-p);
v = sym('th');
dvdth = subs(diff(subs(f,th,v),v),v,th)
Is there any problem with the preceding script?
My example approach that you cite is for a simpler situation. Your function
fdepends on not just abstract symbolic functions, but also their derivatives. The problem is thatsubs(f,th,v)by itself returns zero. This is because the substitution also replaces theth(t)insidediff(th(t),t)with a constant symbolic variable that is not a function of time. The derivative of a constant is zero so your entire function simplifies to zero.To work with an equation like this you need to replace
diff(th(t),t)with something else so that it is not impacted by the substitution. This can be done fairly painlessly by using the multiple substitution capabilities ofsym/subs:Or more compactly (but very hard to read):
These returns
a1*a2*m2*sin(p(t) - th(t))*diff(p(t), t)*diff(th(t), t), which is equivalent to your expected result.As I noted in my StackOverflow answer, this is, in my opinion, an ugly hack. One might be able turn this approach into a general function with a bit of work, but it might be quite challenging to handle every possible case.