Skip to main content

How to multiply two binary gurobi variables using Java?

Answered

Comments

4 comments

  • Maliheh Aramon
    Gurobi Staff Gurobi Staff
    Hi Hadi, 
     
    You can define a Gurobi quadratic expression object (GRBQuadExpr) and iterate through the terms in the GRBLinExpr object already defined and multiply each term by the binary variable \(\texttt{m1}\). Please see the snippet below as an example:
     
    GRBQuadExpr quad_expr = new GRBQuadExpr();
    for (int i=0; i < expr10.size(); ++i) {
    double coeff = expr10.getCoeff(i);
    GRBVar var_1 = expr10.getVar(i);
    quad_expr.addTerm(coeff, var_1, m1);
    }
     
    Best regards,
    Maliheh
    1
  • Hadi Askaripoor
    Gurobi-versary
    Conversationalist
    First Question

    Dear Maliheh,

    Thanks for your reply! If I want to multiply two gurobi  binary variables e.g. k = m1*m2 and then multiply k to the expr10, how can I proceed? I've tried the same method as you explained but it didn't work!  

    I would appreciate your help!

    0
  • Maliheh Aramon
    Gurobi Staff Gurobi Staff

    Hi Hadi, 

    Sorry for the delay in getting back to you. 

    It should work. I tested the snippet below and it works. Could you please try modifying your code based on the example below and re-run it again?

    GRBVar m1 = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "m1");
    GRBVar m2 = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "m2");
    GRBVar k = model.addVar(0.0, 1.0, 0.0, GRB.BINARY, "k");
    // Model k = m1 * m2
    GRBQuadExpr quad_expr_k = new GRBQuadExpr();
    quad_expr_k.addTerm(1, m1, m2);
    model.addQConstr(quad_expr_k, GRB.EQUAL, k, "c1");

    // Multiply k by the linear expression
    GRBQuadExpr quad_expr = new GRBQuadExpr();
    for (int i=0; i < expr10.size(); ++i) {
    double coeff = expr10.getCoeff(i);
    GRBVar var_1 = expr10.getVar(i);
    quad_expr.addTerm(coeff, var_1, k);
    }

    Best regards, 

    Maliheh

    0
  • Hadi Askaripoor
    Gurobi-versary
    Conversationalist
    First Question

    Dear Maliheh,

    It worked, I would really appreciate your help!

    Best regards,

    Hadi

    0

Please sign in to leave a comment.