Get coefficients of symbolic polynomial in Matlab

binomial-coefficients, matlab, polynomial-math, symbolic-math

Solution

You can use `sym2poly` if your polynomial is a function of a single variable like your example `y^2`:

syms y
p = 2*y^2+3*y+4;
c = sym2poly(p)

which returns

c =

     2     3     4

Use `fliplr(c)` if you really want the coefficients in the other order. If you're going to be working with polynomials it would probably also be a good idea not to create a variable called `poly`, which is the name of a function you might want to use.

If you actually need to handle polynomials in multiple variables, you can use MuPAD functions from within Matlab. Here is how you can use MuPAD's `coeff` to get the coefficients in terms of the order of variable they precede (`x` or `y`):

syms x y
p = 2*x^2+3*x*y+4*y;
v = symvar(p);
c = eval(feval(symengine,'coeff',p,v))

If you want to extract all of the information from the polynomial, the `poly2list` function is quite helpful:

syms x y
p = 2*x^2+3*x*y+4*y;
v = symvar(p);
m = eval(feval(symengine,'poly2list',p,v));
c = m(:,1); % Coefficients
degs = m(:,2:end); % Degree of each variable in each term

The polynomial can then be reconstructed via:

sum(c.*prod(repmat(v,[size(m,1) 1]).^degs,2))

By the way, good choice on where you go to school. :-)

Problem

I have a Matlab function that returns a polynomial of the form: ``` poly = ax^2 + bx*y + cy^2 ``` where a, b, and c are constants, and x and y are symbolic (class `sym`). I want to get the coefficients of the polynomial in the form `[a b c]`, but I'm running into the following problem. If the function returns `poly = y^2`, then `coeffs(poly) = 1`. I don't want this – I want it to return `[0 0 1]`. How can I create a function that will give me the coefficients of a symbolic polynomial in the form that I want?

Original source