Here are three ways you can go, using MonomialList
, CoefficientRules
, FromCoefficientRules
and Collect
. The first is the simplest, but I've included the others because they're good to know about if you're dealing with polynomials a lot.
1. MonomialList
MonomialList
will cut up your polynomial into the terms you want. So the simplest way is probably just:
poly = a x^2 y + 2 x z + b z x + c x^2 y + x;
Total@MonomialList[poly, {x, y, z}]
(* x + (a + c) x^2 y + (2 + b) x z *)
2. CoefficientRules
and FromCoefficientRules
This method is slightly more convoluted than MonomialList
, and so isn't really ideal in this situation. But it's well worth knowing that it can be done. CoefficientRules
gets you the exponents and the corresponding coefficients, FromCoefficientRules
reconstructs the polynomial with that form:
FromCoefficientRules[
CoefficientRules[poly, {x, y, z}],
{x, y, z}]
(* x + (a + c) x^2 y + (2 + b) x z *)
3. Collect
with CoefficientRules
You can also get the monomials (power products) you want with
monomials = x^#1 y^#2 z^#3 & @@@ CoefficientRules[poly, {x, y, z}][[;; , 1]]
(* {x^2 y, x z, x} *)
Then Collect
will do the job:
Collect[poly, monomials]
(* x + (a + c) x^2 y + (2 + b) x z *)
Just for reference, it's probably worth comparing that monomials
list with the output from MonomialList
, which is
MonomialList[poly, {x, y, z}]
(* {(a + c) x^2 y, (2 + b) x z, x} *)
That is, monomials
just contains the power products, whereas MonomialList
includes their coefficients. (Confusingly, both can be called "monomials").
Collect[expr, {z, x, y}]
. $\endgroup$