# Re-sorting higher-order ordinary differential equations

I have some higher-order ordinary differential equations.

Firstly, I want to collect the terms with common factors together. Besides, I want to re-sort the ODE with the highest order term first.

How can we write general code/module? I think it would be also useful for other Mathematica users.

For example, let's have a sixth-order ODE as follows:

    (\[Omega] - Subscript[a, 6])*U[\[Eta]]- Subscript[a, 2]*U[\[Eta]] + 5*k^2*Subscript[a, 6]*Derivative[U][\[Eta]] + Subscript[b, 1]*U[\[Eta]]^3 + Subscript[b, 2]*U[\[Eta]]^3 + Subscript[b, 2]*U[\[Eta]]^5 + Subscript[b, 3]*U[\[Eta]]^7 + Subscript[a, 2]*Derivative[U][\[Eta]] + 6*k^2*Subscript[a, 4]*Derivative[U][\[Eta]] +
30*k^3*Subscript[a, 5]*Derivative[U][\[Eta]] + Subscript[a, 4]*Derivative[U][\[Eta]] + 2*k^2*Subscript[a, 6]*Derivative[U][\[Eta]] + Subscript[a, 6]*Derivative[U][\[Eta]] + Subscript[a, 4]*Derivative[U][\[Eta]]==0


So, I want to get the following: • You can collect terms with Collect[eq, {U[_], Derivative[_][U][_]}] where eq is your equation. Sorting the terms is a bit tricky, because Plus is inherently Orderless. Do you want to have the sorted output just for the displaying purposes? Mar 24, 2022 at 15:45
• Thank you for your interest. I see. If what I said is not possible, yes we can sort it for displaying purposes as the last possibility. Mar 24, 2022 at 16:06

Clear["Global*"]

eqn = (ω - Subscript[a, 6])*U[η] - Subscript[a, 2]*U[η] +
5*k^2*Subscript[a, 6]*Derivative[U][η] +
Subscript[b, 1]*U[η]^3 + Subscript[b, 2]*U[η]^3 +
Subscript[b, 2]*U[η]^5 + Subscript[b, 3]*U[η]^7 +
Subscript[a, 2]*Derivative[U][η] +
6*k^2*Subscript[a, 4]*Derivative[U][η] +
30*k^3*Subscript[a, 5]*Derivative[U][η] +
Subscript[a, 4]*Derivative[U][η] +
2*k^2*Subscript[a, 6]*Derivative[U][η] +
Subscript[a, 6]*Derivative[U][η] +
Subscript[a, 4]*Derivative[U][η] == 0;

format = Inactive[Plus] @@
Reverse[List @@ (Collect[#, {U[η], Derivative[_][U][η]}])] &;


Displayed in the requested order

format@eqn[] == 0 In canonical order

% // Activate
` 