How to let the user specify the variable name?

For example, I want the user to specify the variable name of the JuMP mode. How to do?

using JuMP

function fun(var::Symbol)
    model = Model()
    @variable(model, var[1:3])
end

Thanks.

With the base_name keyword argument

using JuMP

function fun(var::Symbol)
    model = Model()
    @variable(model, [1:3], base_name=var)
end
2 Likes

Tkanks!!!

I’ve tried this but failed.

function fun(var::Symbol)
    model = Model()
    @eval @variable(model, $(var)[1:3])
end

It seems that var will not be a registered variable name of the model?

I’ll fail to extract the variable of the model if so

using JuMP

function fun(var::Symbol)
    model = Model()
    @variable(model, [1:3], base_name=var)
end

var = :x
model = fun(var)
y = model[:x]
@constraint(model, y .>= 0)

You need to manually register the variable after setting the name (see the JuMP docs on that), e.g. by using

using JuMP

function fun(var::Symbol)
    model = Model()
    model[var] = @variable(model, [1:3], base_name=var)
    return model
end

var = :x

model = fun(var)
@constraint(model, model[:x] .>= 0)
3 Likes

I see!!! Nice! Didn’t quite understand before. Thanks!