# Collecting multivariate polynomials

In a way of minimal example, say I want to collect the expansion of $(a+b+x+y)^2$ with respect to $x$ and $y$. Collect[(a+b+x+y)^2,{x,y}] gives nested collection (sums involving $y$ as coefficients at powers of $x$) which is not what I want. Most concise code that I could find for it is

Total[Map[Last[#]Times@@({x,y}^First[#])&,CoefficientRules[(a+b+x+y)^2,{x,y}]]]


(which correctly gives a^2 + 2 a b + b^2 + (2 a + 2 b) x + x^2 + (2 a + 2 b) y + 2 x y + y^2).

Is there more straightforward way to do it?

• @MarcoB This results in a^2 + 2ab + b^2 + x^2 + (2a + 2b)y + y^2 + x(2a + 2b + 2y) which is not what I want. Feb 6, 2017 at 9:15
• Oh I see. I was careless in reading the desired format. Feb 6, 2017 at 9:27
• @MarcoB I added explanation about that Feb 6, 2017 at 9:32
• Something like this? In:= Plus @@ MonomialList[Expand[(a + b + x + y)^2], {x, y}] Out= a^2 + 2 a b + b^2 + (2 a + 2 b) x + x^2 + (2 a + 2 b) y + 2 x y + y^2 Feb 6, 2017 at 15:31
• @DanielLichtblau I think this is optimal - at any rate better than my version. Could you please make this an answer? I was not aware of MonomialList. It is very nice also because you can reorder the summands. Feb 6, 2017 at 16:40

One can use MonomialList to separate power products involving a specified set of variables. In this example it might be done as below.

Plus @@ MonomialList[Expand[(a + b + x + y)^2], {x, y}]

(* Out= a^2 + 2 a b + b^2 + (2 a + 2 b) x + x^2 + (2 a + 2 b) y +
2 x y + y^2 *)


Try this:

lst = Rest @ Flatten @ Array[x^# y^#2 &, {3, 3}, 0]

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


and then

 Collect[Expand[(a + b + x + y)^2], lst]

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


Have fun!

• Alexei, your Collect expression does nothing to the expanded multinomial. Indeed, your final output is the same as Expand[(a + b + x + y)^2]. Notice also that it is not what the OP wanted as output. Feb 6, 2017 at 10:27
• @MarcoB The OP writes: "gives nested collection (sums involving y as coefficients at powers of x) which is not what I want". That's how I interpreted his words. If it is not the case he should be more precise. Feb 6, 2017 at 12:32
• Sorry I don't understand. In your version, why are the terms, say, 2ay+2by not collected together like (2a+2b)y?? Feb 6, 2017 at 16:38
• @მამუკა ჯიბლაძე Sorry, it is because I skipped omitting 1 in the first step. I fixed this. Please have a look at the edits. Feb 7, 2017 at 10:16
• Oh I see, good, thanks. I could accept this one too, I only stay with the previous one since I like MonomialList :) Feb 7, 2017 at 16:00