# Get the homogeneous part of a polynomial

What is the easiest or fastest way to extract the homogeneous part of a polynomial in Mathematica. For instance, if there were a function homog_part[f,n], I could use it to extract the second, first and zeroth degree homogeneous part of $f=x^2+y^2+xy+x+y+7$ by writing homog_part[f,2] to get $x^2+y^2+xy$, homog_part[f,1] to get $x+y$ and homog_part[f,0] to get $7$.

I was thinking of using Series, but here you would give individual degrees of each variable while for the homogeneous part you need the total degree.

• A question like this really should be accompanied by test input in cut-and-pasteable form. – Daniel Lichtblau Oct 29 '17 at 14:48
• @Daniel. Apologies. I agree. Some of the answer have these input so I will not add this in the question anymore. But I will keep this in mind for future reference/questions. – quantum May 16 '18 at 14:15

f[x_, y_] = x^2 + y^2 + x y + x + y + 7;
homoPart = Total[Pick[MonomialList[#], Total[CoefficientRules[#][[All, 1]], {2}], #2]] &;
homoPart[f[x, y], #] & /@ Range[0, 3]


{7, x + y, x^2 + x y + y^2, 0}

SeriesCoefficient is useful for this. We just multiply all variables by a new variable and extract a degree term in that.

homogeneousPart[poly_, vars_, deg_] :=
Module[{t},
SeriesCoefficient[poly /. Thread[vars -> t*vars], {t, 0, deg}] /.
t -> 1]


Example:

pol = x^2 + y^2 + x*y + x + y + 7;

Table[homogeneousPart[pol, {x, y}, j], {j, 3, 0, -1}]

(* Out[6]= {0, x^2 + x y + y^2, x + y, 7} *)

• +1 so neat. Nicer than all the manipulation I did with CoefficientRules :) – ubpdqn Oct 30 '17 at 6:51
• This is closely related to Jens's solution here. – J. M. is away Oct 31 '17 at 5:56
• @J.M. Thanks for the link. I see that I upvoted that one. Should have realized this has come up before. – Daniel Lichtblau Oct 31 '17 at 14:13
hp[f_, n_] :=
Total@Cases[{Plus @@ #1, #2 Inner[Power, Variables[f], #1, Times,
1]} & @@@ CoefficientRules[f], {n, w_} :> w]


e.g. hp[f[x,y],#]&/Range[0,2] yields {7, x + y, x^2 + x y + y^2}

or hp[x^3 + 3 x^2 y + 2, #] & /@ Range[0, 3] yields {2, 0, 0, x^3 + 3 x^2 y}