Search code examples
juliadifferentialequations.jl

How to use ModelingToolkit.jl to create variables dynamically


The main problem is that my variables would be determined only after running the codes (because the number of variables is not fixed).

In old version ModelingToolkit.jl, I used the following codes to generate a variable.

my_var = Variable(Symbol(name))(t)  # name is a string

However, it can’t work in the latest version. Here is the error.

ERROR: Sym name is not callable. Use @syms name(var1, var2,...) to create it as a callable.

I've checked SymbolicUtils.jl but didn't find other usages. How can I fix this problem?


Solution

  • You can use the @variables macro to create symbolic variables at runtime as well. The $ operator interpolates the runtime value.

    julia> using ModelingToolkit
    
    julia> z = :abc;
    
    julia> k = @variables $z
    1-element Vector{Num}:
     abc
    
    julia> k[1]
    abc