0
$\begingroup$

I want to solve an optimization problem using the CPLEX API in C++. After solving the model, I then want to resolve it using a different objective function.

For that purpose, I learned the functions setLinearCoef(...) and setLinearCoefs(...) exist.

Here's my current code for a small reproducable example:

#include <iostream>
#include <ilcplex/ilocplex.h>

int main() {

    int benefitOfZ = 7;

    IloEnv env;
    IloModel Model2(env);

    IloNumVarArray Z(env, 5, 0, IloInfinity, ILOFLOAT);

    IloExpr expr_obj2(env);
    for (int i = 0; i < 5; i++) {
        expr_obj2 += benefitOfZ * Z[i];
    }
    IloObjective obj2 = (IloMaximize(env, expr_obj2));
    Model2.add(obj2);

    // Constraint 3
    for (int i = 0; i < 5; i++) {
        Model2.add(Z[i] <= 2);
    }
  
    IloCplex cplex2(Model2);
    cplex2.solve();

    std::cout << "Objective Value of Model 2: " << cplex2.getObjValue() << std::endl;

    benefitOfZ = 14;

    for (int i = 0; i < 5; i++) {
        obj2.setLinearCoef(Z[i], benefitOfZ);
    }
    cplex2.solve();
    std::cout << "Objective Value of Model 2 after change: " << cplex2.getObjValue() << std::endl;

    return 0;
}

Now this works how I intend it to. But I read in the documentation that setLinearCoefs(...) is more efficient than setLinearCoef(...).

I tried changing the code accordingly but I can't get it work without errors. The main problem is that I don't properly understand how I need to build the objective function so that I can use setLinearCoefs(...) afterwards on it.

Does someone know how I could reformulate my code to make it work?

$\endgroup$

1 Answer 1

2
$\begingroup$

In your current code, benefitOfZ is a scalar constant and Z[i] is a scalar variable. To use setLinearCoefs, you would make Z the first argument, and for the second argument you would need to create an instance of IloNumArray containing the new objective coefficients.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.