How to Append Polynomial to 5-element vector if the highest order is less than 4? Polynomials.jl Package

Hi all I have a problem here,

I want to calculate special sum by using Polynomials.jl, thus it works fine if there is one of degree 4, but if the highest input is of degree 2, the coeffs(p) would become 3-element vector, and we need to append the last two elements by 0 so we can still make the calculation of

a*(coeffs(p))

this is the code:

using Symbolics, Polynomials
@variables n i 

a = [1 n*(n+1)/2 n*(n+1)*(2n+1)/6 (1/4)*(n*(n+1))^2 (n*(n+1)*(2n+1)*(3n^2 + 3n - 1))/30]

# 1 + 2i -> Polynomial([1,2,0,0], :i)
# 3i^2 + i^4 -> Polynomial([0,0,3,0,1], :i)
# i^2 - 3i - 10 -> Polynomial([-10,-3,1,0,0], :i)

p = Polynomial([-10,-3,1,0,1], :i)

# coeffs(p) -> returns the entire coefficient vector
# Polynomials.degree(p) -> returns the polynomial degree, length is 1 plus the degree
println("The special sum for $p is")

a*(coeffs(p))

Anyone know how to append polynomial to 5-element vector with zeroes ? if the input polynomial is less than order of 4?

Thus, if I input this:

p = Polynomial([-10,-3,1,0,0], :i)

it would become still 5-element vector: [-10; -3; -1; 0; 0] instead of 3-element vector [-10;-3;1]

either use if-else conditional or any idea?

Does this pad function solve the problem?

julia> pad(v,n) = (L = length(v) ; 
  [i <= L ? v[i] : zero(eltype(v)) for i in 1:n] )
pad (generic function with 1 method)

julia> pad(coeffs(p),5)
5-element Vector{Int64}:
 -10
  -3
   1
   0
   0

pad(v,n) will return vector of length n with elements from v where valid and zero otherwise.
A similar function might exist in some library, or might be added as it sounds useful.

1 Like

Wow @Dan Amazing!

How did you know about this pad(v,n), this is what I need. Thanks a lot! All the best for you