I am pretty new to Python and Gurobi. I want to add a binary variable for several "dimensions":
A = [1,2,3,4]
B = [1,2,3,4]
C = [1,2,3,4,5]
D = [1,2,3]
I need the binary variable x with indices A,B,C,D.
I am not sure how to use the command:
m.addVars()
This is how you create variables from a given index list:
import gurobipy as gp
A = [1,2,3,4]
model = gp.Model()
variables = model.addVars(A, name='A', vtype='B')
After calling model.update()
, you see these variable names/types:
{1: <gurobi.Var A[1]>,
2: <gurobi.Var A[2]>,
3: <gurobi.Var A[3]>,
4: <gurobi.Var A[4]>}
This is also explained in the documentation . You simply repeat this process for the other lists B
, C
, and D
.
EDIT
Another alternative to combine all indices into one variable structure is the following:
A = [1,2,3,4]
B = [1,2]
C = [1,2,3]
model = gp.Model()
variables = model.addVars(A, B, C, vtype='B')
You would access these variables like this:
variables[1,2,1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.