There two methods using which you could define objective functions.
=====================================================
The first one is to define the objective explicitly:
GRBVar x = SimpleExample.addVar(0, 50, 20, GRB_CONTINUOUS, "x"); // Define variable x in the model and its range (0-50)
GRBVar y = SimpleExample.addVar(0, 100, 30, GRB_CONTINUOUS, "y"); // Define variable y in the model and its range (0-100)
SimpleExample.setObjective(20*x+30*y, GRB_MINIMIZE); // Define the objective function as to minimize 20x+30y
If you notice, the addVar function has 5 entries in this case:
- The lower bound of the variable
- The upper bound of the variable
- The coefficient of the variable in the objective function
- Variable type (such as continuous or integer)
- Tag for the variable
If you define the objective function explicitly, then the 3rd entry (the coefficient of the variable in the objective function) of the addVar function will not be used. You could enter 0 for the 3rd entry of the addVar function, but your objective function will still be defined as what you explicitly define (20x+30y in the example’s case).
Using this approach, you could define not only linear objective functions but also nonlinear objective functions, such as min(20x^2+30y^2).
=====================================================
The second one is to automatically define the objective function:
GRBVar x = SimpleExample.addVar(0, 50, 20, GRB_CONTINUOUS, "x"); // Define variable x in the model and its range (0-50)
GRBVar y = SimpleExample.addVar(0, 100, 30, GRB_CONTINUOUS, "y"); // Define variable y in the model and its range (0-100)
SimpleExample.set(GRB_IntAttr_ModelSense, GRB_MINIMIZE); // Define the objective function as to minimize 20x+30y
In this case, you need to clearly specify the coefficients for each variable in the addVar function, then the entry GRB_IntAttr_ModelSense will automatically form a linear expression using the variables and their coefficients that are defined. However, if you do this, the objective function has to be linear.