# Extract monomials with a certain structure from a given polynomial

I have a long polynomial such as

a x^2+ bx^2y+cx^2y^2 +d x^3y^4+e x^4y^3+f y^2+g xy^2


Consider an example problem as follows: I want to output the monomials (along with their coefficients) which have y^2 in them and then write down a polynomial using them. In other words, if y^2 is not contained in the monomial, I want to set its coefficient to 0 and write down the resulting polynomial. For example, the above polynomial will lead to the following

0 x^2+ 0 x^2y+cx^2y^2 +0 x^3y^4+ 0 x^4y^3+f y^2+g xy^2 = cx^2y^2+fy^2+gxy^2


Can MonomialList extract the monomials with a certain structure like the above example?

• I assume you want spaces between adjacent letters (e.g. b * x^2y, not bx^2y which equals (bx)^2y since bx is treated as a single variable. Apr 19 at 20:05
• y^2 Coefficient[expr, y^2]?
– kglr
Apr 19 at 20:07

expr = a x^2 + b x^2 y + c x^2 y^2 + d x^3 y^4 + e x^4 y^3 + f y^2 +  g x y^2;

y^2 Coefficient[expr, y^2]

(f + g x + c x^2) y^2

Expand @ %

f y^2 + g x y^2 + c x^2 y^2

TeXForm @ %


$$c x^2 y^2+f y^2+g x y^2$$

You can also use

Plus @@ Cases[ _. y^2] @ expr

ReplaceAll[Except[_. y^2, _Times] -> 0] @ expr

Expand @ First @ Cases[_. y^2] @ MonomialList[expr, y]


If the polynomial is expanded, then perhaps this:

Replace[
a x^2 + b x^2 y + c x^2 y^2 + d x^3 y^4 + e x^4 y^3 + f y^2 +
g x y^2,
term_ /; FreeQ[term, y^2] -> 0,
1]
(*  f y^2 + g x y^2 + c x^2 y^2  *)


Toward this end, we need to test all terms of the polynomial on level 1. We can do this using "Replace" with a level specification. We then need to test if the term does not contain "y^2" and set these terms to zero. This can be done with a corresponding rule:

poly = a  x^2 + b x^2 y + c x^2 y^2 + d x^3 y^4 + e x^4 y^3 + f y^2 +
g x y^2
Replace[poly , x_?(FreeQ[y^2]) :> 0, {1}]


Using GroupBy and Lookup:

Lookup[GroupBy[MonomialList[expr], ! FreeQ[#, y^2] &, Total], True]

(*f y^2 + g x y^2 + c x^2 y^2*)