3
$\begingroup$

Is there a way to collect coefficients on specific linear combinations of variables? Consider the example below:

expression = a x1 + (b^2)/3 y1 + z1 - a x2 - (b^2)/3 y2

I would like to output the collected coefficients on the linear combinations (x1 - x2) and (y1 - y2), that is

a (x1 - x2) + (b^2)/3 (y1 - y2) + z1

Thanks.

$\endgroup$
2
  • 2
    $\begingroup$ To literally Collect use a temporary change of variables: Collect[expression /. {x1 -> v1 + x2, y1 -> v2 + y2}, {v1, v2}] /. {v1 -> x1 - x2, v2 -> y1 - y2} $\endgroup$
    – Bob Hanlon
    Commented May 22, 2020 at 14:38
  • $\begingroup$ Yes, this works indeed, very simple and elegant solution. Would be happy to vote it as an answer! $\endgroup$
    – user191919
    Commented May 22, 2020 at 15:02

2 Answers 2

5
$\begingroup$
expression = a x1 + (b^2)/3 y1 + z1 - a x2 - (b^2)/3 y2;

To literally Collect, use a temporary change of variables :

Collect[expression /. {x1 -> v1 + x2, y1 -> v2 + y2},
  {v1, v2}] /. {v1 -> x1 - x2, v2 -> y1 - y2}

(* a (x1 - x2) + 1/3 b^2 (y1 - y2) + z1 *)
$\endgroup$
2
  • $\begingroup$ As a quick follow-up, is there a way to prevent mathematica from doing any simplification at all in the output? For example, naturally mathematica will simplify x - x to 0. $\endgroup$
    – user191919
    Commented May 22, 2020 at 15:26
  • 1
    $\begingroup$ If you use HoldForm, HoldPattern, or similar then no simplifications will be made; however, you also cannot manipulate the expression in any fashion. $\endgroup$
    – Bob Hanlon
    Commented May 22, 2020 at 15:38
4
$\begingroup$
FullSimplify[expression]
 a (x1 - x2) + 1/3 b^2 (y1 - y2) + z1
$\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.