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[[1]]; rhs = eqn[[2]];

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.

  • $\begingroup$ use Simplify it will arrange the equation and terms $\endgroup$
    – nufaie
    Mar 20, 2019 at 16:33
  • 1
    $\begingroup$ @Alrubaie, no it does not. $\endgroup$ Mar 20, 2019 at 16:34

1 Answer 1


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[[2]] . v == -arrays[[1]]

For your example:

rearrange[eqn] //TeXForm

$x_3-2 x_4+x_5=-2 \zeta _3+\zeta _6+\zeta _7-\zeta _9-r_0$

  • $\begingroup$ 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? $\endgroup$ Mar 20, 2019 at 17:15
  • 1
    $\begingroup$ @leastaction Does the documentation for Cases help? $\endgroup$
    – Carl Woll
    Mar 20, 2019 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.