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?
a^2 + 2ab + b^2 + x^2 + (2a + 2b)y + y^2 + x(2a + 2b + 2y)
which is not what I want. $\endgroup$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
$\endgroup$MonomialList
. It is very nice also because you can reorder the summands. $\endgroup$