# 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 '17 at 9:15
• Oh I see. I was careless in reading the desired format. – MarcoB Feb 6 '17 at 9:27
• @MarcoB I added explanation about that – მამუკა ჯიბლაძე Feb 6 '17 at 9:32
• Something like this? In[1514]:= Plus @@ MonomialList[Expand[(a + b + x + y)^2], {x, y}] Out[1514]= a^2 + 2 a b + b^2 + (2 a + 2 b) x + x^2 + (2 a + 2 b) y + 2 x y + y^2 – Daniel Lichtblau Feb 6 '17 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 '17 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[1549]= 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. – MarcoB Feb 6 '17 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. – Alexei Boulbitch Feb 6 '17 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 '17 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. – Alexei Boulbitch Feb 7 '17 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 '17 at 16:00