LoadError: UndefVarError: @variables not defined

I got the error ‘LoadError: UndefVarError: @variables not defined’ while testing the code provided by ModelingToolkits webpage Solving Nonlinear Systems with NLsolve · ModelingToolkit.jl

Here is the code:

begin
	using ModelingToolkit
	using JuMP
	
	@variables x y z
	@parameters σ ρ β
	
	# Define a nonlinear system
	eqs = [0 ~ σ*(y-x),
	       0 ~ x*(ρ-z)-y,
	       0 ~ x*y - β*z]
	ns = NonlinearSystem(eqs, [x,y,z], [σ,ρ,β])
	nlsys_func = generate_function(ns)[2] # second is the inplace version
end

Much appreciated if someone could help.

It’s probably because ModelingToolkit and JuMP both export @variables. They aren’t the same thing, so you need to prefix which one you want. (Did it show a warning talking about multiple packages exporting the same name?)

begin
	using ModelingToolkit
	using JuMP
	
	ModelingToolKit.@variables x y z
	@parameters σ ρ β
	

It seems like you don’t need JuMP here, so you should probably just remove it. Then you won’t hit this problem.

It can also be caused by the fact that the using statement and the macro calls are in the same expression (the begin block). Because macros are evaluated before the expression code is run this could explain that it is not yet defined. You can try to move it in multiple blocks:

begin
    using ModelingToolkit
end

begin
    ModelingToolkit.@variables x y z
    # the rest of the code...
end
1 Like