JuliaSymbolics / Symbolics.jl

Symbolic programming for the next generation of numerical software
https://symbolics.juliasymbolics.org/stable/
Other
1.33k stars 147 forks source link

It would be interesting to be able to create an array of subscripted symbolic variables automatically #694

Open mvainstein opened 1 year ago

mvainstein commented 1 year ago

It would be nice to automatically create an array of subscripted variables given n with Symbolics:

For the case n=6, I would like to do what the code below does without having to type out the variables explicitly.

using Polynomials, Symbolics

@variables a₂ a₃ a₄ a₅ a₆
a = [0, 0, a₂, a₃, a₄, a₅, a₆]
p = Polynomial(a)

From the Symbolics docs, it is possible to do something like

@variables a[1:3]

but then I cannot start the array from index 0 or from another arbitrary value, which is what I want so that the index of the array matches the exponent of the monomial. I have managed to do this with Sympy, but would like to have the same kind of array with Symbolics.

bowenszhu commented 1 year ago

Try this https://github.com/JuliaSymbolics/Symbolics.jl/blob/da72404e92ad6894697f741747bfd828ff9df516/src/variable.jl#L450-L452 https://github.com/JuliaSymbolics/Symbolics.jl/blob/da72404e92ad6894697f741747bfd828ff9df516/src/variable.jl#L470-L477

using Symbolics
as = Symbolics.variables(:a, 0:3)

gives

4-element Vector{Num}:
 a₀
 a₁
 a₂
 a₃

And

using Symbolics
@variables t
as = Symbolics.variables(:a, 0:3, -1:2; T = Symbolics.FnType)
as = map(a -> a(t), as)

result:

4×4 Matrix{Num}:
 a₀ˏ₋₁(t)  a₀ˏ₀(t)  a₀ˏ₁(t)  a₀ˏ₂(t)
 a₁ˏ₋₁(t)  a₁ˏ₀(t)  a₁ˏ₁(t)  a₁ˏ₂(t)
 a₂ˏ₋₁(t)  a₂ˏ₀(t)  a₂ˏ₁(t)  a₂ˏ₂(t)
 a₃ˏ₋₁(t)  a₃ˏ₀(t)  a₃ˏ₁(t)  a₃ˏ₂(t)
mvainstein commented 1 year ago

Thanks! It worked.

ChrisRackauckas commented 9 months ago

No the suggested form is just to interpolate into the macro. I.e. @variables $x with some symbol for the name. This looks like in full:

x = :somesymbol
y = only(@variables($x))

where y is now the Julia name to a variable that is programmatically generated to have a name matching the symbol from the value of x.

The above post does not instantiate the metadata.

It would be nice for a simpler function to exist but it does not right now.