4
$\begingroup$

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]]

$\endgroup$
11
  • $\begingroup$ CoefficientList will provide the matrix of all of the coefficients. With this list you could reproduce the polynomial. $\endgroup$
    – Bob Hanlon
    Commented May 21, 2022 at 16:25
  • $\begingroup$ No, CoefficientList[x+2y+3xy] doesn't work. $\endgroup$
    – Thrash
    Commented May 21, 2022 at 16:26
  • 1
    $\begingroup$ I'm interested only in the rational coefficients, so in both polynomials you have given they are essentially {1,2,3} (up to ordering). $\endgroup$
    – Thrash
    Commented May 21, 2022 at 16:43
  • 1
    $\begingroup$ Then Values@CoefficientRules[..] seems easiest. $\endgroup$
    – Michael E2
    Commented May 21, 2022 at 16:45
  • 1
    $\begingroup$ 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. $\endgroup$
    – Michael E2
    Commented May 21, 2022 at 16:48

2 Answers 2

3
$\begingroup$

One can apply

Values@CoefficientRules@p

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

$\endgroup$
1
$\begingroup$

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

123

Second solution

foo[function_] := 
 Sort[Numerator[(List @@ (function /. 
       Thread[Variables[function] -> 1/Variables[function]]))]]

and then

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

to get

123

$\endgroup$

Your Answer

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

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