7
$\begingroup$

I have a bunch of linear equations of the form

x[1] == 5012 - 5x[3] - 2x[4] + 5x[7]

etc. Specifically there is one linear variable on the left, and the right-hand side is linear (generically with a constant).

I want to process these so that all the variables come on the left and the constant stays on the right. So for the above I would want

x[1] + 5x[3] + 2x[4] - 5x[7] == 5012

as the output. This feels like a very simple thing to try and do but I am struggling to implement it.

$\endgroup$

4 Answers 4

4
$\begingroup$

Try

eq = x[1] == 5012 - 5 x[3] - 2 x[4] + 5 x[7]
expr = eq /. Equal -> Subtract;
const = expr /. Map[# -> 0 &,  Variables[expr]]
neweq=expr - const == -const 
(*x[1] + 5 x[3] + 2 x[4] - 5 x[7] == 5012*)
$\endgroup$
2
  • $\begingroup$ Thank you -- this does just what I needed $\endgroup$
    – Facieod
    Commented Sep 15, 2023 at 13:26
  • $\begingroup$ You're welcome! $\endgroup$ Commented Sep 15, 2023 at 13:27
7
$\begingroup$
tran = SubtractSides[SubtractSides[#], First@CoefficientArrays[#]] &;
eqn=x[1] == 5012 - 5x[3] - 2x[4] + 5x[7];
tran[eqn]

x[1] + 5 x[3] + 2 x[4] - 5 x[7] == 5012

eqns = {x[1] == 5012 - 5 x[3] - 2 x[4] + 5 x[7], 
  x[1] + 2 x[4] == -5 x[3] + 5 x[7] + 5012, 
  5012 == x[1] + 5 x[3] + 2 x[4] - 5 x[7]};
tran/@eqns

{x[1] + 5 x[3] + 2 x[4] - 5 x[7] == 5012, x[1] + 5 x[3] + 2 x[4] - 5 x[7] == 5012, -x[1] - 5 x[3] - 2 x[4] + 5 x[7] == -5012}

$\endgroup$
3
$\begingroup$
eq = x[1] == 5012 - 5 x[3] - 2 x[4] + 5 x[7]
vars = Variables[Subtract @@ eq]
ca = CoefficientArrays[eq] // Normal
vars .  Last[ca] == First@ca

x[1] + 5 x[3] + 2 x[4] - 5 x[7] == -5012

$\endgroup$
2
$\begingroup$

Here is yet another way. Check if the expression is of type Plus or not. If type Plus, loop over each term and move those to the right that do not depend on the variable. If not type Plus, do nothing.

ClearAll["Global`*"];
adjust[eq_Equal] := Module[{expr, vars, lhs = 0, rhs = 0, n},
  expr = First@SubtractSides[eq];
  vars = Variables[expr];
  If[Head[expr] === Plus,
   Do[
    If[Internal`DependsOnQ[expr[[n]], vars],
     lhs = lhs + expr[[n]]
     ,
     rhs = rhs - expr[[n]]
     ]
    ,
    {n, 1, Length@expr}
    ];
   lhs == rhs
   ,
   expr == 0
   ]
  ]

Now

 adjust[x[1] == 5012 - 5 x[3] - 2 x[4] + 5 x[7]]

Mathematica graphics

adjust[x[1] + 34 + y + z == -300]

Mathematica graphics

adjust[x[1] + 34 == -300 + Log[z] - Pi/2]

Mathematica graphics

$\endgroup$

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.