# Collect with linear combinations

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.

• 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} Commented May 22, 2020 at 14:38
• Yes, this works indeed, very simple and elegant solution. Would be happy to vote it as an answer! Commented May 22, 2020 at 15:02

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 *)

• 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. Commented May 22, 2020 at 15:26
• If you use HoldForm, HoldPattern, or similar then no simplifications will be made; however, you also cannot manipulate the expression in any fashion. Commented May 22, 2020 at 15:38
FullSimplify[expression]

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