With Mathematica I would like collect terms from (1 + a + x + y)^4 according to the exponents of x and y, so
(1 + a + x + y)^4 = (...)x^0 y^0 + (...)x^1 y^0 + (...)x^0 y^1 + ...
The Mathematica help has a nice example which I tried to imitate:
D[f[Sqrt[ x^2 + 1 ]], {x, 3}]
Collect[%, Derivative[ _ ][ f ][ _ ], Together]
This collects derivative terms of the same order (and the same argument for f)
Can anyone explain why the following imitation does not work?
Collect[(1 + a + x + y)^4, x^_ y^_]
gives
(1 + a + x + y)^4
Any suggestions for a solution?
As per Sasha, you have to
Expandthe polynomial to useCollect. However, even then it isn’t that simple of a problem. UsingCollectyou can group by two variables, but it depends on how you order them:which pulls out any common factor of
xresulting in coefficients that are polynomials iny. If you used{y,x}instead,Collectwould pull out the common factors ofyand you’d have polynomials inx.Alternatively, you could supply a pattern,
x^_ y^_instead of{x,y}, but at least in v.7, this does not collect anything. The issue is that the patternx^_ y^_requires an exponent to be present, but in terms likex y^2andx^2 ythe exponent is implicit in at least one of the variables. Instead, we need to specify that a default value is acceptable, i.e. usex^_. y^_.which givesBut, this only collects terms where both variables are present. Truthfully, I can’t seem to come up with a pattern that would make
Collectfunction like you want, but I have found an alternative.I’d use
CoefficientRulesinstead, although it does require a little post-processing to put the result back into polynomial form. Using your polynomial, you getNow, if you’re only interested in the coefficients themselves, then you’re done. But, to transform this back into a polynomial, I’d use
Edit: After thinking about it, there is one more simplification that can be done. Since the coefficients are polynomials in
a, they may be factorable. So, instead of using whatCoefficientRulesgives directly, we useFactorto simplify:As can be seen, the coefficients are considerably simplified by using
Factor, and this result could have been anticipated by thinking of(1 + a + x + y)^4as a simple trinomial with variables(1 + a),x, andy. With that in mind and replacing1+awithz,CoefficientRulesthen gives:Or, in polynomial form
which when you replace
zwith(1 + a)gives the identical result shown inOut[5].