Adding variables to the model

Once we create a Gurobi model, we can start adding variables and constraints to it. In our example, we'll begin by adding variables:


/* Add variables */ obj[0] = 1; obj[1] = 1; obj[2] = 2; vtype[0] = GRB_BINARY; vtype[1] = GRB_BINARY; vtype[2] = GRB_BINARY; error = GRBaddvars(model, 3, 0, NULL, NULL, NULL, obj, NULL, NULL, vtype, NULL); if (error) goto QUIT;

The first argument toGRBaddvars()is the model to which the variables are being added. The second is the number of added variables (3 in our example).

Arguments three through six describe the constraint matrix coefficients associated with the new variables. The third argument gives the number of non-zero constraint matrix entries associated with the new variables, and the next three arguments give details on these non-zeros. In our example, we'll be adding these non-zeros when we add the constraints. Thus, the non-zero count here is zero, and the following three arguments are allNULL.

The seventh argument toGRBaddvars()is the linear objective coefficient for each new variable. Since our example aims to maximize the objective, and by default Gurobi will minimize the objective, we'll need to change the objective sense. This is done in the next statement. Note we could have multiplied the objective coefficients by -1 instead (since maximizing<span>$</span>c'x<span>$</span>is equivalent to minimizing<span>$</span>-c'x<span>$</span>).

The next two arguments specify the lower and upper bounds of the variables, respectively. TheNULLvalues indicate that these variables should take their default values (0.0 and 1.0 for binary variables).

The tenth argument specifies the types of the variables. In this example, the variables are all binary (GRB_BINARY).

The final argument gives the names of the variables. In this case, we allow the variable names to take their default values (x0, x1, and x2).