# How can I manipulate a long expression to order it by factors/derivatives of a particular function?

I have a Mathematica notebook that generates a linear expression involving derivatives of a given variable. Expanded (and simplified for our purposes), it looks something like this:

\begin{equation} A g^{(1,0)} + B g^{(0,1)} + C + D g^{(1,1)} + E g^{(0,2)} + F g^{(1,1)} + G + H g^{(0,1)} + I + J g^{(2,0)} + K g^{(0,1)} + L g^{(1,0)} + M g^{(1,1)} \end{equation}

In general, the function $g\rightarrow g(x,y)$ all coefficients ($A, B, C, ...$) are complicated functions of $x$ and $y$ composed of yet other functions, but I have omitted them above for brevity. Upon inspection, you can see that the above expression could be reordered:

\begin{equation} A g^{(1,0)} + L g^{(1,0)} + J g^{(2,0)} + B g^{(0,1)} + H g^{(0,1)} + K g^{(0,1)} + E g^{(0,2)} + D g^{(1,1)} + F g^{(1,1)} + M g^{(1,1)}+ C + G + I \end{equation}

This would lead naturally to something useful to me:

\begin{equation} (A+L) g^{(1,0)} + J g^{(2,0)} + (B+H+K) g^{(0,1)} + E g^{(0,2)} + (D+F+M) g^{(1,1)} + (C+G+I) \end{equation}

My end goal is to simplify each of the terms above to get a new expression of the form

\begin{equation} U g^{(1,0)} + V g^{(2,0)} + W g^{(0,1)} + X g^{(0,2)} + Y g^{(1,1)} + Z \end{equation}

Unfortunately, Simplify and FullSimplify choose to order the expression based on other variables and functions inside my coefficients. It produces terms like this instead:

\begin{equation} \frac{a(g^{(1,0)}-g^{(0,1)})}{b} c \end{equation}

where $a$ and $b$ are complicated expressions and $c$ is a variable found inside several of the other coefficients $A, B, C, ...$. I want to order the expression by factors of $g$ rather than order by variables like $c$.

In the past, I have done something like FactorTerms[someLongExpression[x,y],blah], where $blah = \{g^{(1,0)},g^{(2,0)},g^{(0,1)},g^{(0,2)},g^{(1,1)}\}$, hoping to get something like the second expression above, where the terms are ordered. From there, I copy/paste/simplify each group of terms in a separate notebook and bring the results back to my working notebook. This does not even group the terms correctly for my case, however, and I have a hunch that it could be done more simply.

I think the following code will do the trick:

Collect[expr, Derivative[_, _][g][_, _]]


If you want Mathematica to try to simplify each "coefficient", you can use this version instead:

Collect[expr, Derivative[_, _][g][_, _], Simplify]


I can't claim full credit for this code — there's an example in the "Scope" section of the documentation for Collect that does this for derivatives of a function of a single variable.

• That totally works! Thanks! Jun 26, 2015 at 20:16