How to determine the coefficients of a polynom

How can I determine the coefficients of a polynom?

using Symbolics

@variables R a b c d U J Q s

input = 2s + 4U*a*s^2 + Q*(J+s)

function split_s(input::Num)
end

res = split_s(input)

# expected output:
# the factors of s², of s and without s
# [4U*a, 2+Q, Q*J]

here maybe you’ll find some ideas for your problem

1 Like
split_s(input::Num, v::Num) = 
  vcat([Symbolics.coeff(input, v^i) for i in Symbolics.degree(input, v):-1:1],
  substitute(input, v => 0))

gives:

julia> split_s(input,s)
  4U*a
 2 + Q
   J*Q
1 Like

Perfect! Thank you very much.

My code now:

function split_s(input)
    inp = simplify(input, expand=true)
    vcat([Num(Symbolics.coeff(inp, s^i)) for i in Symbolics.degree(inp, s):-1:1],
    substitute(inp, s => 0))
end

two questions:
what is the need to have Num() wrapped on Symbolics.coeff(inp, s^i)?
why doesn’t Symbolics.coeff(inp, s^0) give what you would expect?

You are right, this was done quite hastily. I’ll remove it from the answer. TBH not really an expert on Symbolics.jl, just fiddled around. Oops… my code doesn’t actually have this. Was confused by reply to me. Tagging @ufechner7

If I do not wrap this I get an vector of any, and if I then try to create a transfer function with tf(num, den) it fails.

julia> include("mwes/mwe20.jl")
4-element Vector{Any}:
  4U*a
 0
  2 + Q + J*Q
 0

julia> input
2s + (s + J*s)*Q + 4U*a*(s^3)

It seems like someone has already thought of this feature.
The biggest difficulty is understanding that the second argument must be a tuple.

julia> polynomial_coeffs(input, s)
ERROR: MethodError: no method matching iterate(::SymbolicUtils.BasicSymbolic{Real})


julia> polynomial_coeffs(input, (s,))
(Dict{Any, Any}(s^2 => 4U*a, s => 2 + Q, 1 => J*Q), 0)


help?> polynomial_coeffs
search: polynomial_coeffs

  polynomial_coeffs(expr, vars)


  Find coefficients of a polynomial in vars.

  Returns a tuple of two elements:

    1. A dictionary of coefficients keyed by
       monomials in vars

    2. A residual expression which is the
       constant term
1 Like