There is a very convenient function Dt
that allows to take a total differential of any expression, e.g.:
expr = (a + b c)/d;
Dt[expr]
(Dt[a] + c Dt[b] + b Dt[c])/d - ((a + b c) Dt[d])/d^2
Consider a case where expr
is generic (it is not known a priori which and how many variables appear). I would like to have a function that extracts a list of all Dt[x_]
from an expression. For the above example it should do:
extract[Dt[expr]]
{Dt[a],Dt[b],Dt[c],Dt[d]}
My own version of this function is:
extract[x_] := Select[Variables[x], (Head[#] === Dt) &]
but I feel like extracting all variables and then selecting a subset is too hacky. Is there a nice way to implement this?
EDIT
Bob Hanlon and Mr. Wizard suggested to use Cases
and Union
. Unfortunately, these functions appear to be slower than the above in some cases:
Select[Variables[ Dt[(a + b c)/d + (a + b c)/d q]], (Head[#] === Dt) &] // AbsoluteTiming
{0.0000811731, {Dt[a], Dt[b], Dt[c], Dt[d], Dt[q]}}
compared to
Cases[Dt[(a + b c)/d + (a + b c)/d q], _Dt, {-2}] // Union // AbsoluteTiming
{0.000136221, {Dt[a], Dt[b], Dt[c], Dt[d], Dt[q]}}
Cases[Dt[expr], _Dt, Infinity] // Union
$\endgroup$Cases[Dt[expr], _Dt, {-2}] // Union
-- the single level search should be somewhat faster with large expressions as well. $\endgroup$Union@Cases[expr, HoldPattern[Dt[_]], Infinity]
$\endgroup$