Thomas W.
Thomas W.

Reputation: 2224

Iterate over terms in Julia's dynamic polynomials

In Julia, I've defined a polynomial using DynamicPolynomials, e.g.:

using DynamicPolynomials
@polyvar x y
p = x + y + x^2 + x*y + y^2
cx = rand(10)
cy = rand(10)

Now I would like to iterate over the terms of the polynomial and evaluate the terms at x=cx[i] and y=cy[i]. How can I do this? Finally, I would like to create a matrix M[i, j] = t[j]([cx[i], cy[i]]), where t[j]is the j-th term of the polynomial p.

Upvotes: 0

Views: 224

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69829

I guess you can do it directly. Here is an example:

using DynamicPolynomials
@polyvar x y
p = x + y + x^2 + x*y + y^2
cx = 1:10
cy = 11:20

and now

julia> res = [t(x=>vx,y=>vy) for (vx, vy) in zip(cx,cy), t in p]
10×5 Array{Int64,2}:
   1   11  121   1  11
   4   24  144   2  12
   9   39  169   3  13
  16   56  196   4  14
  25   75  225   5  15
  36   96  256   6  16
  49  119  289   7  17
  64  144  324   8  18
  81  171  361   9  19
 100  200  400  10  20

You can annotate row and column to check more easily that you get what you want in the following way:

julia> using NamedArrays

julia> NamedArray(res, (collect(zip(cx,cy)), collect(p)), ("point", "term"))
10×5 Named Array{Int64,2}
point ╲ term │ x^2   xy  y^2    x    y
─────────────┼────────────────────────
(1, 11)      │   1   11  121    1   11
(2, 12)      │   4   24  144    2   12
(3, 13)      │   9   39  169    3   13
(4, 14)      │  16   56  196    4   14
(5, 15)      │  25   75  225    5   15
(6, 16)      │  36   96  256    6   16
(7, 17)      │  49  119  289    7   17
(8, 18)      │  64  144  324    8   18
(9, 19)      │  81  171  361    9   19
(10, 20)     │ 100  200  400   10   20

Upvotes: 1

Related Questions