Question

I am using Cplex in Java and I have a probem with setting up a constraint.

I've got a matrix x[n][n], where x can be 0 or 1. For every i(1..n) the sum of all j(1..n) = 1

Regarding the answer in this post: Cplex c++ multidimensional decision variable , I set up my code like this:

for (int i=0; i<n; i++){
            IloNumExpr sum_over_i;
            for(int j=0; j<n; j++){
                sum_over_i += x[i][j];
            }   
            cplex.addEq(sum_over_i, 1.0);
        }

For the 4th line of the code java shows this error: "The operator += is undefined for the argument type(s) IloNumExpr, IloNumVar"

Is it possible that assignment operators like "+=" work for cplex c++ but not for cplex java?

As an alternative, I tried this:

for(int i=0; i<n; i++){
            IloNumExpr sum_over_i = null;
            for(int j=0; j<n; j++){
                cplex.eq(sum_over_i, cplex.sum(sum_over_i, x[i][j]));
            }   
            cplex.addEq(sum_over_i, 1.0);
        }

In this case Eclipse comes up with this error note when running:

Exception in thread "main" java.lang.NullPointerException
at ilog.cplex.CpxQextractor.visitLinkedExpr(CpxQextractor.java:73)
at ilog.cplex.CpxLinkedExpr.accept(CpxLinkedExpr.java:46)
at ilog.cplex.CpxRange.<init>(CpxRange.java:1337)
at ilog.cplex.IloCplexModeler.makeRange(IloCplexModeler.java:4316)
at ilog.cplex.IloCplexModeler.eq(IloCplexModeler.java:4902)
at TSP.main(TSP.java:57)

Can anybody tell me whats wrong about my code?

Thanks in advance.

Was it helpful?

Solution

I remember also having a very hard time finding an example of how to do linear expressions in the CPLEX Java API, although the documentation in general for CPLEX is very good.

To do the constraints "For every i(1..n) the sum of all j(1..n) = 1" I would do

for(int i=0; i < n; i++) {
  IloLinearNumExpr lhs = cplex.linearNumExpr(); //lhs as in left hand side
  for(int j=0; j < n; j++) {
    lhs.addTerm(1.0, x[i][j]);        
  }   

  IloRange con = cplex.addEq(lhs, 1);
  con.setName("yourConstraintName(" + i + ")");      
}

You don't need to set a name for your constraint but it will always help you debug your model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top