How to define a symbolic vector using for loop with Symbolics.jl?

Dear all,

How to define a symbolic vector using for loop with Symbolics.jl?
For example, x=[x1, x2, x3, x4, …, x100], where xi are all variables defined using @variables.
It can be easily done using sympy.jl as
julia> N=100, x = [symbols(“x$i”) for i in 1:N].

Please note that I must use Symbolics.jl for the sake of speed and complicated matrix manipulation.
I am aware of the symbolic arrays introduced at Symbolic arrays · Symbolics.jl,
but it does not work.

Cheers,

Sean

This might do it:

julia> [getfield(Main, Symbol("x$i")) for i in 1:3]
3-element Vector{Num}:
 x1
 x2
 x3

But, perhaps it is better to go this route:

julia> @variables y[1:3]
1-element Vector{Symbolics.Arr{Num, 1}}:
 y[1:3]

Thanks. Neither of them work.

julia> [getfield(Main, Symbol(“x$i”)) for i in 1:3]

ERROR: UndefVarError: x1 not defined

@variables y[1:3] does not contain variables xi.

The getfield works if variables are defined in a global scope. If variables are defined locally, a better solution would be to do:

xvars = @variables x1 x2 x3

and then xvars already contains a vector of all the x vars.

The Main in first option is the Module name where the xis are defined, if it is in another module, then replace this Main with the name of module or more generally:

[getfield(@__MODULE__, Symbol(“x$i”)) for i in 1:3]

As for other option, it is a suggestion to go in a different way than defining many xis in a long @variables line.

Hopefully this clarification will help.

Thanks. Defining xi using “@variables x1 x2 x3” is exactly my problem. How do use for loop with @variables to define xi?

Hopefully I understood this time and:

@eval @variables $([Symbol("x$i") for i=1:3]...)

is what you were looking for.

A symbolic vector and a vector of symbols are different things. For a vector of symbols, use the interpolation syntax, i.e.

sym = :x1
@variables $sym # (defines a variable x1)

Thank you @Dan @ChrisRackauckas for your reply.
The following post and the referred one shows how to do

1 Like