MATLAB: Chain rule with symbolic functions

MATLABsymbolic differentiation

I define the following symbolic variables:
syms s k mu2(s,k) mu3(s,k) mu4(s,k)
>> mu2(s, k) = 1 + 6*k^2 - 24*k*s^2 + 25*s^4;
>> mu3(s,k) = 108*k^2*s - 468*k*s^3 + 36*k*s + 510*s^5 - 76*s^3 + 6*s;
>> mu4(s,k) = 3 + 3348*k^4 - 28080*s^2*k^3 + 1296*k^3 - 6048*s^2*k^2 ...
+ 252*k^2 - 123720*s^6*k + 8136*s^4*k - 504*s^2*k ...
+ 24*k + 64995*s^8 - 2400*s^6 - 42*s^4 + 88380*k^2*s^4;
>>
>> Scap = mu3(s,k)/mu2(s,k)^3/2
Scap =(108*k^2*s - 468*k*s^3 + 36*k*s + 510*s^5 - 76*s^3 + 6*s)/(2*(6*k^2 - 24*k*s^2 + 25*s^4 + 1)^3)
When I take the 1st derivative of Scap with respect to s I would expect MatLab to apply the chain rule as Scap is not directly a function of s. Instead I get the following:
>> diff(Scap,s)
ans =
(108*k^2 - 1404*k*s^2 + 36*k + 2550*s^4 - 228*s^2 + 6)/(2*(6*k^2 - 24*k*s^2 + 25*s^4 + 1)^3) + (3*(- 100*s^3 + 48*k*s)*(108*k^2*s - 468*k*s^3 + 36*k*s + 510*s^5 - 76*s^3 + 6*s))/(2*(6*k^2 - 24*k*s^2 + 25*s^4 + 1)^4)
How can I have MatLab explicitly apply the chain rule ?
Thank you so much
mauede

Best Answer

The definition
Scap = mu3(s,k)/mu2(s,k)^3/2
is procedural not symbolic. The current values of mu3(s,k) and mu2(s,k) are fetched and substituted, giving the expression you see, which is a direct function of s that has no "memory" of being formed by mu3 and mu2 .
If you want explicit chain rule in terms of mu2 and mu3, then you need to define Scap first in terms of mu2 and mu3 and do the differentiation before you give the formula for mu2 and mu3.
syms s k mu2(s,k) mu3(s,k) mu4(s,k) Scap(s,k)
Scap = mu3(s,k)/mu2(s,k)^3/2;
dScap = diff(Scap(s,k),s) %explicit chain rule result
mu2(s, k) = 1 + 6*k^2 - 24*k*s^2 + 25*s^4;
mu3(s,k) = 108*k^2*s - 468*k*s^3 + 36*k*s + 510*s^5 - 76*s^3 + 6*s;
subs(dScap) %substitute the defined mu2 and mu3 into the chain rule
Related Question