Symbolic Toolbox: Coefficients and Powers of a polynomial
7 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Haroon
on 21 Jan 2019
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)
0 Comments
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!