# Collect terms in a polynom, distributed

Consider the following expression

in = a x^2 y + 2 x z + b z x + c x^2 y + x ;


I would like to collect terms in $(x,y,z)$ in a distributive way, that is

out = (a+c) x^2 y + (2+b) x z + x;


I tried the following command

Collect[expr,{x,y,z}]
Collect[expr,{x,y,z},Factor]
Collect[expr,{x,y,z},Simplify]


But here is the output:

Out[2]= (a + c) x^2 y + x (1 + (2 + b) z)

Out[3]= (a + c) x^2 y + x (1 + (2 + b) z)

Out[4]= (a + c) x^2 y + x (1 + (2 + b) z)

• Try this: Collect[expr, {z, x, y}]. – Anjan Kumar Nov 22 '17 at 17:58
• Ok it will work on this example, but I would like a generic way for general examples. In fact I am looking for the Maple's equivalent to collect(expr,[x,y,z],'distributed'); – Smilia Nov 22 '17 at 18:00
• Possible duplicate: mathematica.stackexchange.com/questions/152362/… – Anjan Kumar Nov 22 '17 at 18:15

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

MonomialListwill 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").

Try this:

expr = a x^2 y + 2 x z + b z x + c x^2 y + x;

lst = (Table[x^n*y^m*z^k, {n, 0, 2}, {m, 0, 1}, {k, 0, 1}] //
Flatten) /. x_ /; x == 1 -> Nothing

(*  {z, y, y z, x, x z, x y, x y z, x^2, x^2 z, x^2 y, x^2 y z}  *)


and then

Collect[expr, lst]

(*   x + (a + c) x^2 y + (2 + b) x z  *)


Have fun!