5
$\begingroup$

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.

$\endgroup$
  • 3
    $\begingroup$ A question like this really should be accompanied by test input in cut-and-pasteable form. $\endgroup$ – Daniel Lichtblau Oct 29 '17 at 14:48
  • $\begingroup$ @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. $\endgroup$ – quantum May 16 '18 at 14:15
7
$\begingroup$
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}

$\endgroup$
6
$\begingroup$

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} *)
$\endgroup$
  • $\begingroup$ +1 so neat. Nicer than all the manipulation I did with CoefficientRules :) $\endgroup$ – ubpdqn Oct 30 '17 at 6:51
  • $\begingroup$ This is closely related to Jens's solution here. $\endgroup$ – J. M. will be back soon Oct 31 '17 at 5:56
  • $\begingroup$ @J.M. Thanks for the link. I see that I upvoted that one. Should have realized this has come up before. $\endgroup$ – Daniel Lichtblau Oct 31 '17 at 14:13
4
$\begingroup$
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}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.