Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mvainstein opened this issue Aug 9, 2022 · 3 comments

Comments

@mvainstein
Copy link

mvainstein commented Aug 9, 2022

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
Copy link
Member

bowenszhu commented Aug 9, 2022

Try this

function variables(name, indices...; T=Real)
[variable(name, ij...; T=T) for ij in Iterators.product(indices...)]
end

function variable(name, idx...; T=Real)
name_ij = Symbol(name, join(map_subscripts.(idx), "ˏ"))
if T <: FnType
first(@variables $name_ij(..))
else
first(@variables $name_ij::T)
end
end

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
Copy link
Author

Thanks! It worked.

@ChrisRackauckas
Copy link
Member

ChrisRackauckas commented Oct 7, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants