Oftentimes you find yourself looking for polynomials in multiple variables. Consider the following expression:
a(x - y)^3 + b(x - y) + c(x - y) + d as you can see this is clearly a polynomial in x-y. Is there an equivalent of Collect, that works on more complicated expressions than just a single variable? I would like to have something similar to
Collect[%, x - y] (* --> a(x - y)^3 + (b+c)(x - y) + d *) however. Collect can not work on x-y. Of course you could solve this first example by substituting x-y -> z, then Collect the z, and afterwards substitute back like so:
a(x - y)^3 + b(x - y) + c(x - y) + d /. x-y->z gives
d + b z + c z + a z^3 Then
Collect[a z^3 + b z + c z + d, z] gives
d + (b + c) z + a z^3 Now undo the substitution by running % /. z -> x - y. This gives the desired result:
d + (b + c) (x - y) + a (x - y)^3 So this is good. For obvious polynomials, we can solve this. But what about real world examples? Would you have guessed that
d + b x + c x + a x^3 - b y - c y - 3 a x^2 y + 3 a x y^2 - a y^3 is exactly the same polynomial? How would you Collect x-y here, as you cannot do the substitution?
expr /. x -> y + zbefore applyingCollect[](and possiblySimplify[]before that) myself... $\endgroup$Module[{z},Collect[expr/.x->y+z,z]/.z->x-y]. The only limitation is thatexprmust not containz. Or useCollect[expr/.x->y+#,#]/.#->x-y]&@Unique[]to lift even that limitation. $\endgroup$