# Rearranging similar terms in an equation

In a piece of code I am writing, I run into an equation of the form

eqn = Subscript[x, 3] + Subscript[x, 5] + Subscript[r, 0] + 2 Subscript[ζ, 3] + Subscript[ζ, 9] == 2 Subscript[x, 4] + Subscript[ζ, 6] + Subscript[ζ, 7]

In more readable $$\LaTeX$$ format, this looks like

$$x_3 + x_5 + r_0 + 2 \zeta_3 + \zeta_9 = 2 x_4 + \zeta_6 + \zeta_7$$

Given such an equation with Subscript[x, __] as the variable of interest, I would like to rewrite it with all $$x_i$$'s on the left hand side and everything else on the right-hand side, i.e.

$$x_3 - 2 x_4 + x_5 = -r_0 - 2\zeta_3 + \zeta_6 + \zeta_7 - \zeta_9$$

(I am not interested in the TeXForm of course. That is trivial to extract if needed.)

Now given such an equation (eqn) I can extract the left and right hand sides as

lhs = eqn[]; rhs = eqn[];

Then the variables on each side are

vLHS = Variables[lhs]; vRHS = Variables[rhs];

But how does one rearrange the equations like so?

EDIT: I already have a solution that strips each side of the equation, looks for what involves $$x_i$$ and what doesn't and reconstructs the equation in this way (by manipulating it as a list). I want to know if there's a more elegant solution.

• use Simplify it will arrange the equation and terms Mar 20 '19 at 16:33
• @Alrubaie, no it does not. Mar 20 '19 at 16:34

Maybe you can do something like the following:

rearrange[eqn_] := Module[{v, arrays},
v = Union @ Cases[eqn, Subscript[x, _], Infinity];
arrays = CoefficientArrays[eqn, v];
arrays[] . v == -arrays[]
]


rearrange[eqn] //TeXForm

$$x_3-2 x_4+x_5=-2 \zeta _3+\zeta _6+\zeta _7-\zeta _9-r_0$$
• Perfect, thank you Carl! That works great. In an effort to understand the code, I executed each line outside the module in the interactive notebook. I just have one question: Why does levelspec equal to Infinity work? Mar 20 '19 at 17:15
• @leastaction Does the documentation for Cases help? Mar 20 '19 at 17:48