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?

  • $\begingroup$ 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. $\endgroup$
    – Michael E2
    Apr 19 at 20:05
  • 1
    $\begingroup$ y^2 Coefficient[expr, y^2]? $\endgroup$
    – kglr
    Apr 19 at 20:07

4 Answers 4

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:

 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,
(*  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}] 

enter image description here


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*)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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