Symbolic Toolbox: Coefficients and Powers of a polynomial

3 次查看(过去 30 天)
Hey,
suppose I have a (maybe multidimensional) polynomial given in a symbolic way. What I want is all the coefficients of the different terms with knowledge about the power of the variable at this point. So a perfect solution would be something like this
Input: 3 * x^5 + 2 * x^3 + 23
Output: Coeffs: [3 2 23], Powers: [5 3 0]
Or something like the polynomial in matlab, i.e.
output: [3 0 2 0 0 23]
I actually wrote a small script than can already do what I want:
syms x
f = 3 * x^5 + 2 * x^3 + 23
[polyCoeffs, mononomials] = coeffs(f)
% output is
% polyCoeffs = [ 3, 2, 23]
% mononomials = [ x^5, x^3, 1]
polyPowers = zeros(1, length(mononomials))
for i=1:length(mononomials)
polyPowers(i) = length(sym2poly(polyPowers(i))) - 1;
end
It does the job, but it is very unelegant and - if there are more than one variable in the polynomial - in can get a little bit more complicated. So I'd like to know if anyone has a smarter idea, or if there is something in Matlab I just haven't found yet.
Thanks

回答(2 个)

Haroon
Haroon 2019-1-21
The above code will not work well. I have modified it and now it is working fine.
syms x
f = 3 * x^5 + 2 * x^3 + 23
[polyCoeffs, mononomials] = coeffs(f);
poly=sym2poly(f);
polyPowers = zeros(1, length(mononomials));
j=0;
for i=1:length(poly)
if poly(i)~=0
j=j+1;
polyPowers(j)= length(poly)-i;
end
end
display(polyPowers)

Mohamad Hejazi Dinan
Use the function polyPowers

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by