# Vector of monomials of order up to n?

Suppose I have a scalar x. Then producing the vector [1,x,x^2, \ldots,x^n] is straightforward,

``````[x^i for i in 0:n]
``````

What if x is a vector, x=[x_1,\dots,x_{n_x}], and I want to produce the vector [1, x_1, \ldots,x_{n_x}, x_1^2, x_1 x_2, \ldots, x_1 x_{n_x}, x_2^2, x_2 x_3, \ldots, x_1^n, x_1^{n-1}x_2, \ldots ]. How can I do that in the simplest and most elegant/efficient way? Is there a package for this?

Use the Combinatorics package:

``````using Combinatorics

prods(x, n) = collect(Iterators.flatten((prod(y) for y in with_replacement_combinations(x, i)) for i = 0:n))
``````

For example, using the SymPy package to apply this to symbolic variables, I get:

4 Likes

Thanks! I’ll test it to see if I understand it :-).

It works perfectly as I wanted it to! Thanks!

1 Like