# Coefficients of a multivariate polynomial

Let's say I have the polynomial $$x+2y+3xy \in \mathbb Q[x,y]$$ or $$x_1+2x_2+3x_1x_2 \in \mathbb Q[x_1,x_2]$$, that is x+2y+3xy or x[1]+2x[2]+3x[1]x[2]. Is there a simple command to get all the coefficients at once, that is {1,2,3}?

So far, the following works for the latter case (based on the ordering of MonomialList), but is there perhaps a more intuitive way?

MonomialList[x[1]+2x[2]+3x[1]x[2]] /. x[i_Integer] -> 1

MonomialList[x[1]+2x[2]+3x[1]x[2]] /. _x -> 1

Edit: I've found a method (based on the ordering of CoefficientRules) that can be used for both cases. It seems that this is the easiest way.

Values@CoefficientRules[x+2y+3xy]

Values@CoefficientRules[x[1]+2x[2]+3x[1]x[2]]

• CoefficientList will provide the matrix of all of the coefficients. With this list you could reproduce the polynomial. Commented May 21, 2022 at 16:25
• No, CoefficientList[x+2y+3xy] doesn't work. Commented May 21, 2022 at 16:26
• I'm interested only in the rational coefficients, so in both polynomials you have given they are essentially {1,2,3} (up to ordering). Commented May 21, 2022 at 16:43
• Then Values@CoefficientRules[..] seems easiest. Commented May 21, 2022 at 16:45
• You could post it as a self-answer. Also Union@Values@CoefficientList[..] would sort the results and delete duplicates, in case you want to treat the coefficients as a set. Commented May 21, 2022 at 16:48

One can apply

Values@CoefficientRules@p

to a given polynomial p to get its coefficients (according to the ordering of CoefficientRules).

Two more suggestions. I have taken the comments into consideration.

The test cases are:

poly1 = x + 2 y + 3 x y;
poly2 = x[1] + 2 x[2] + 3 x[1] x[2];
poly3 = x + 3 x y + 2 x^2;


First solution

foo[function_] := Cases[function, x_. y___ :> x, {1}]


and then

foo[poly1]
foo[poly2]
foo[poly3]


to get

Second solution

foo[function_] :=
Sort[Numerator[(List @@ (function /.

foo[poly1]