# How to collect terms with z-derivative?

my equations are very long (several pages). Here I will provide simple example:

eq = (g[x, y, z, t])^2*D[D[f[x, y, z, t], {x, 1}] {z, 1}] + \[Alpha]*
f[x, y, z, t]*D[D[g[x, y, z, t], {y, 1}], {z, 2}] +
g[x, y, z, t]*D[D[f[x, y, z, t], {t, 1}] {z, 2}]+D[f[x,y,z,t],{z,2}]


So, it has several functions, constant parameters, and consists of the sum of some terms. Each term is the product of some number of these functions and it's derivatives.

I want to collect, or sort, these terms according to z-derivative. So, first, I want to sort these terms according to the highest z-derivative of the function f[x,y,z,t]. So, in the example above, first term should be g[x, y, z, t]*D[D[f[x, y, z, t], {t, 1}] {z, 2}]+D[f[x,y,z,t],{z,2}], as long as it has second derivatives of the function f[x,y,z,t] over z. After that it should be (g[x, y, z, t])^2*D[D[f[x, y, z, t], {x, 1}] {z, 1}], and then f[x, y, z, t]*D[D[g[x, y, z, t], {y, 1}], {z, 2}].

Note, that the derivative could be taken over several arguments, like g[x, y, z, t]*D[D[f[x, y, z, t], {t, 1}] {z, 2}].

I looked through the examples of Collect, but didn't find a way to specify z-derivative, as a second argument. Also it would be good, if you point out, how to show only the terms with z derivatives.

I'm sure there is an easier and shorter way of doing this so consider this a starting point.

A strange thing I noticed is that when I copied and pasted your equation into a notebook it turned into a list.

eq = g[x, y, z, t]^2*D[D[f[x, y, z, t], {x, 1}] {z, 1}] +
α*f[x, y, z, t]*D[D[g[x, y, z, t], {y, 1}], {z, 2}] +
g[x, y, z, t]*D[D[f[x, y, z, t], {t, 1}] {z, 2}] +
D[f[x, y, z, t], {z, 2}] I continue to be mystified by this however we need to take it into account.

Step 1 - Strip curly brackets

eq = eq[] Step 2 - Break it into parts

eqList = eq[[#]] & /@ Range[Length[eq]] This effectively breaks it at the plus sign.

Step 3 - Sort the parts

This is the significant portion. We will use the value of the zth derivative to do the sorting.

sortedEqList =
Sort[eqList,
Total@Cases[#1,
Derivative[i_Integer, j_Integer, k_Integer, l_Integer][f | g][x,
y, z, t] -> k, {0, Infinity}] >
Total@Cases[#2,
Derivative[i_Integer, j_Integer, k_Integer, l_Integer][f | g][x,
y, z, t] -> k, {0, Infinity}] &] Step 4 - Join the sorted parts

If you merely rejoin the parts using Plus they will be sorted back to the original order so use Inactive.

Inactive[Plus] @@ sortedEqList • Thanks a lot! That perfectly works for me! – Mikhail Genkin Oct 20 '15 at 21:17
• Advise that you wait a couple of days before accepting. It is highly probable that someone will provide a better answer. You should select the best answer, not the fastest. – Jack LaVigne Oct 20 '15 at 22:22
• Got it, thanks. – Mikhail Genkin Oct 21 '15 at 21:10