/* Copyright 2025, Gurobi Optimization, LLC *//* This example formulates and solves the following simple QP model: minimize x + y + x^2 + x*y + y^2 + y*z + z^2 subject to x + 2 y + 3 z >= 4 x + y >= 1 x, y, z non-negative The example illustrates the use of dense matrices to store A and Q (and dense vectors for the other relevant data). We don't recommend that you use dense matrices, but this example may be helpful if you already have your data in this format.*/importcom.gurobi.gurobi.*;publicclassDense{protectedstaticbooleandense_optimize(GRBEnvenv,introws,intcols,double[]c,// linear portion of objective functiondouble[][]Q,// quadratic portion of objective functiondouble[][]A,// constraint matrixchar[]sense,// constraint sensesdouble[]rhs,// RHS vectordouble[]lb,// variable lower boundsdouble[]ub,// variable upper boundschar[]vtype,// variable types (continuous, binary, etc.)double[]solution){booleansuccess=false;try{GRBModelmodel=newGRBModel(env);// Add variables to the modelGRBVar[]vars=model.addVars(lb,ub,null,vtype,null);// Populate A matrixfor(inti=0;i<rows;i++){GRBLinExprexpr=newGRBLinExpr();for(intj=0;j<cols;j++)if(A[i][j]!=0)expr.addTerm(A[i][j],vars[j]);model.addConstr(expr,sense[i],rhs[i],"");}// Populate objectiveGRBQuadExprobj=newGRBQuadExpr();if(Q!=null){for(inti=0;i<cols;i++)for(intj=0;j<cols;j++)if(Q[i][j]!=0)obj.addTerm(Q[i][j],vars[i],vars[j]);for(intj=0;j<cols;j++)if(c[j]!=0)obj.addTerm(c[j],vars[j]);model.setObjective(obj);}// Solve modelmodel.optimize();// Extract solutionif(model.get(GRB.IntAttr.Status)==GRB.Status.OPTIMAL){success=true;for(intj=0;j<cols;j++)solution[j]=vars[j].get(GRB.DoubleAttr.X);}model.dispose();}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());e.printStackTrace();}returnsuccess;}publicstaticvoidmain(String[]args){try{GRBEnvenv=newGRBEnv();doublec[]=newdouble[]{1,1,0};doubleQ[][]=newdouble[][]{{1,1,0},{0,1,1},{0,0,1}};doubleA[][]=newdouble[][]{{1,2,3},{1,1,0}};charsense[]=newchar[]{'>','>'};doublerhs[]=newdouble[]{4,1};doublelb[]=newdouble[]{0,0,0};booleansuccess;doublesol[]=newdouble[3];success=dense_optimize(env,2,3,c,Q,A,sense,rhs,lb,null,null,sol);if(success){System.out.println("x: "+sol[0]+", y: "+sol[1]+", z: "+sol[2]);}// Dispose of environmentenv.dispose();}catch(GRBExceptione){System.out.println("Error code: "+e.getErrorCode()+". "+e.getMessage());e.printStackTrace();}}}
Help and Feedback