How to collect coefficients of the same powers?

484 Views Asked by At

I am using the Symbolic Math Toolbox, and define polynomials as symbolic objects, e.g.:

syms a x y;
P = x^2*y + a*x*y^2 + x*y^2;

I am looking for a function that collects coefficients of the same powers – something like

collect_coeff(P,x*y^2)

that will return

a + 1

Would anyone have a solution to my problem?

1

There are 1 best solutions below

0
On BEST ANSWER

You can use MuPAD's coeff (documentation) to accomplish this within Matlab:

syms a x y;
P = x^2*y + a*x*y^2 + x*y^2;
feval(symengine,'coeff',P,'[x,y]','[1,2]')
% or equivalently:
%evalin(symengine,'coeff(P,[x,y],[1,2])')

which returns a + 1. I recommend reading the full documentation for coeff and related MuPAD functions for manipulating symbolic polynomials.