Search code examples
type-conversionjuliajulia-jump

How to convert type of a variable when using JuMP


I am using Julia/JuMP to implement an algorithm. In one part, I define a model with continues variables and solve the linear model. I do some other calculations based on which I add a couple constraints to the model, and then I want to solve the same problem but with integer variables. I could not use convert() function as it does not take variables.

I tried to define the variable again as integer, but the model did not seem to consider it! I provide a sample code here:

m = Model()
@defVar(m, 0 <= x <= 5)
@setObjective(m, Max, x)
@addConstraint(m, con, x <= 3.1)
solve(m) 
println(getValue(x))
@defVar(m, 0 <= x <= 1, Bin)
solve(m) 
println(getValue(x))

Would you please help me do this conversion?


Solution

  • The problem is that the second @variable(m, 0 <= x <= 1, Bin) actually creates a new variable in the model, but with the same name in Julia.

    To change a variable from a continuous to a binary, you can do

    setcategory(x, :Bin)
    

    to change the variable bounds and class before calling solve again.