Hide navigation sidebar
Hide table of contents sidebar
Back to top
Toggle table of contents sidebar

# Dense Examples

This section includes source code for all of the Gurobi dense examples. The same source code can be found in the `examples` directory of the Gurobi distribution.

    /* 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.
    */

    #include <stdlib.h>
    #include <stdio.h>
    #include "gurobi_c.h"

    /*
      Solve an LP/QP/MILP/MIQP represented using dense matrices.  This
      routine assumes that A and Q are both stored in row-major order.
      It returns 1 if the optimization succeeds.  When successful,
      it returns the optimal objective value in 'objvalP', and the
      optimal solution vector in 'solution'.
    */

    static int
    dense_optimize(GRBenv *env,
                   int     rows,
                   int     cols,
                   double *c,     /* linear portion of objective function */
                   double *Q,     /* quadratic portion of objective function */
                   double *A,     /* constraint matrix */
                   char   *sense, /* constraint senses */
                   double *rhs,   /* RHS vector */
                   double *lb,    /* variable lower bounds */
                   double *ub,    /* variable upper bounds */
                   char   *vtype, /* variable types (continuous, binary, etc.) */
                   double *solution,
                   double *objvalP)
    {
      GRBmodel *model = NULL;
      int       i, j, optimstatus;
      int       error = 0;
      int       success = 0;

      /* Create an empty model */

      error = GRBnewmodel(env, &model, "dense", cols, c, lb, ub, vtype, NULL);
      if (error) goto QUIT;

      error = GRBaddconstrs(model, rows, 0, NULL, NULL, NULL, sense, rhs, NULL);
      if (error) goto QUIT;

      /* Populate A matrix */

      for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++) {
          if (A[i*cols+j] != 0) {
            error = GRBchgcoeffs(model, 1, &i, &j, &A[i*cols+j]);
            if (error) goto QUIT;
          }
        }
      }

      /* Populate Q matrix */

      if (Q) {
        for (i = 0; i < cols; i++) {
          for (j = 0; j < cols; j++) {
            if (Q[i*cols+j] != 0) {
              error = GRBaddqpterms(model, 1, &i, &j, &Q[i*cols+j]);
              if (error) goto QUIT;
            }
          }
        }
      }

      /* Optimize model */

      error = GRBoptimize(model);
      if (error) goto QUIT;

      /* Write model to 'dense.lp' */

      error = GRBwrite(model, "dense.lp");
      if (error) goto QUIT;

      /* Capture solution information */

      error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
      if (error) goto QUIT;

      if (optimstatus == GRB_OPTIMAL) {

        error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, objvalP);
        if (error) goto QUIT;

        error = GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, cols, solution);
        if (error) goto QUIT;

        success = 1;
      }

    QUIT:

      /* Error reporting */

      if (error) {
        printf("ERROR: %s\n", GRBgeterrormsg(env));
        exit(1);
      }

      /* Free model */

      GRBfreemodel(model);

      return success;
    }

    int
    main(int   argc,
         char *argv[])
    {
      GRBenv *env     = NULL;
      int     error   = 0;
      double  c[]     = {1, 1, 0};
      double  Q[3][3] = {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}};
      double  A[2][3] = {{1, 2, 3}, {1, 1, 0}};
      char    sense[] = {'>', '>'};
      double  rhs[]   = {4, 1};
      double  lb[]    = {0, 0, 0};
      double  sol[3];
      int     solved;
      double  objval;

      /* Create environment */

      error = GRBloadenv(&env, "dense.log");
      if (error) goto QUIT;

      /* Solve the model */

      solved = dense_optimize(env, 2, 3, c, &Q[0][0], &A[0][0], sense, rhs, lb,
                              NULL, NULL, sol, &objval);

      if (solved)
        printf("Solved: x=%.4f, y=%.4f, z=%.4f\n", sol[0], sol[1], sol[2]);

    QUIT:

      /* Free environment */

      GRBfreeenv(env);

      return 0;
    }

    /* 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.
    */

    #include "gurobi_c++.h"
    using namespace std;

    static bool
    dense_optimize(GRBEnv* env,
                   int     rows,
                   int     cols,
                   double* c,     /* linear portion of objective function */
                   double* Q,     /* quadratic portion of objective function */
                   double* A,     /* constraint matrix */
                   char*   sense, /* constraint senses */
                   double* rhs,   /* RHS vector */
                   double* lb,    /* variable lower bounds */
                   double* ub,    /* variable upper bounds */
                   char*   vtype, /* variable types (continuous, binary, etc.) */
                   double* solution,
                   double* objvalP)
    {
      GRBModel model = GRBModel(*env);
      int i, j;
      bool success = false;

      /* Add variables to the model */

      GRBVar* vars = model.addVars(lb, ub, NULL, vtype, NULL, cols);

      /* Populate A matrix */

      for (i = 0; i < rows; i++) {
        GRBLinExpr lhs = 0;
        for (j = 0; j < cols; j++)
          if (A[i*cols+j] != 0)
            lhs += A[i*cols+j]*vars[j];
        model.addConstr(lhs, sense[i], rhs[i]);
      }

      GRBQuadExpr obj = 0;

      for (j = 0; j < cols; j++)
        obj += c[j]*vars[j];
      for (i = 0; i < cols; i++)
        for (j = 0; j < cols; j++)
          if (Q[i*cols+j] != 0)
            obj += Q[i*cols+j]*vars[i]*vars[j];

      model.setObjective(obj);

      model.optimize();

      model.write("dense.lp");

      if (model.get(GRB_IntAttr_Status) == GRB_OPTIMAL) {
        *objvalP = model.get(GRB_DoubleAttr_ObjVal);
        for (i = 0; i < cols; i++)
          solution[i] = vars[i].get(GRB_DoubleAttr_X);
        success = true;
      }

      delete[] vars;

      return success;
    }

    int
    main(int   argc,
         char *argv[])
    {
      GRBEnv* env = 0;
      try {
        env = new GRBEnv();
        double c[] = {1, 1, 0};
        double  Q[3][3] = {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}};
        double  A[2][3] = {{1, 2, 3}, {1, 1, 0}};
        char    sense[] = {'>', '>'};
        double  rhs[]   = {4, 1};
        double  lb[]    = {0, 0, 0};
        bool    success;
        double  objval, sol[3];

        success = dense_optimize(env, 2, 3, c, &Q[0][0], &A[0][0], sense, rhs,
                                 lb, NULL, NULL, sol, &objval);

        cout << "optimal=" << success << " x: " << sol[0] << " y: " << sol[1] << " z: " << sol[2] << endl;

      } catch(GRBException e) {
        cout << "Error code = " << e.getErrorCode() << endl;
        cout << e.getMessage() << endl;
      } catch(...) {
        cout << "Exception during optimization" << endl;
      }

      delete env;
      return 0;
    }

    /* 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.
    */

    using System;
    using Gurobi;

    class dense_cs {

      protected static bool
        dense_optimize(GRBEnv    env,
                       int       rows,
                       int       cols,
                       double[]  c,      // linear portion of objective function
                       double[,] Q,      // quadratic portion of objective function
                       double[,] A,      // constraint matrix
                       char[]    sense,  // constraint senses
                       double[]  rhs,    // RHS vector
                       double[]  lb,     // variable lower bounds
                       double[]  ub,     // variable upper bounds
                       char[]    vtype,  // variable types (continuous, binary, etc.)
                       double[]  solution) {

        bool success = false;

        try {
          GRBModel model = new GRBModel(env);

          // Add variables to the model

          GRBVar[] vars = model.AddVars(lb, ub, null, vtype, null);

          // Populate A matrix

          for (int i = 0; i < rows; i++) {
            GRBLinExpr expr = new GRBLinExpr();
            for (int j = 0; j < cols; j++)
              if (A[i,j] != 0)
                expr.AddTerm(A[i,j], vars[j]); // Note: '+=' would be much slower
            model.AddConstr(expr, sense[i], rhs[i], "");
          }

          // Populate objective

          GRBQuadExpr obj = new GRBQuadExpr();
          if (Q != null) {
            for (int i = 0; i < cols; i++)
              for (int j = 0; j < cols; j++)
                if (Q[i,j] != 0)
                  obj.AddTerm(Q[i,j], vars[i], vars[j]); // Note: '+=' would be much slower
            for (int j = 0; j < cols; j++)
              if (c[j] != 0)
                obj.AddTerm(c[j], vars[j]); // Note: '+=' would be much slower
            model.SetObjective(obj);
          }

          // Solve model

          model.Optimize();

          // Extract solution

          if (model.Status == GRB.Status.OPTIMAL) {
            success = true;

            for (int j = 0; j < cols; j++)
              solution[j] = vars[j].X;
          }

          model.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }

        return success;
      }

      public static void Main(String[] args) {
        try {
          GRBEnv env = new GRBEnv();

          double[] c = new double[] {1, 1, 0};
          double[,] Q = new double[,] {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}};
          double[,] A = new double[,] {{1, 2, 3}, {1, 1, 0}};
          char[] sense = new char[] {'>', '>'};
          double[] rhs = new double[] {4, 1};
          double[] lb = new double[] {0, 0, 0};
          bool success;
          double[] sol = new double[3];

          success = dense_optimize(env, 2, 3, c, Q, A, sense, rhs,
                                   lb, null, null, sol);

          if (success) {
            Console.WriteLine("x: " + sol[0] + ", y: " + sol[1] + ", z: " + sol[2]);
          }

          // Dispose of environment
          env.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
      }
    }

    /* 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.
    */

    import com.gurobi.gurobi.*;

    public class Dense {

      protected static boolean
        dense_optimize(GRBEnv     env,
                       int        rows,
                       int        cols,
                       double[]   c,      // linear portion of objective function
                       double[][] Q,      // quadratic portion of objective function
                       double[][] A,      // constraint matrix
                       char[]     sense,  // constraint senses
                       double[]   rhs,    // RHS vector
                       double[]   lb,     // variable lower bounds
                       double[]   ub,     // variable upper bounds
                       char[]     vtype,  // variable types (continuous, binary, etc.)
                       double[]   solution) {

        boolean success = false;

        try {
          GRBModel model = new GRBModel(env);

          // Add variables to the model

          GRBVar[] vars = model.addVars(lb, ub, null, vtype, null);

          // Populate A matrix

          for (int i = 0; i < rows; i++) {
            GRBLinExpr expr = new GRBLinExpr();
            for (int j = 0; j < cols; j++)
              if (A[i][j] != 0)
                expr.addTerm(A[i][j], vars[j]);
            model.addConstr(expr, sense[i], rhs[i], "");
          }

          // Populate objective

          GRBQuadExpr obj = new GRBQuadExpr();
          if (Q != null) {
            for (int i = 0; i < cols; i++)
              for (int j = 0; j < cols; j++)
                if (Q[i][j] != 0)
                  obj.addTerm(Q[i][j], vars[i], vars[j]);
            for (int j = 0; j < cols; j++)
              if (c[j] != 0)
                obj.addTerm(c[j], vars[j]);
            model.setObjective(obj);
          }

          // Solve model

          model.optimize();

          // Extract solution

          if (model.get(GRB.IntAttr.Status) == GRB.Status.OPTIMAL) {
            success = true;

            for (int j = 0; j < cols; j++)
              solution[j] = vars[j].get(GRB.DoubleAttr.X);
          }

          model.dispose();

        } catch (GRBException e) {
          System.out.println("Error code: " + e.getErrorCode() + ". " +
              e.getMessage());
          e.printStackTrace();
        }

        return success;
      }

      public static void main(String[] args) {
        try {
          GRBEnv env = new GRBEnv();

          double c[] = new double[] {1, 1, 0};
          double Q[][] = new double[][] {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}};
          double A[][] = new double[][] {{1, 2, 3}, {1, 1, 0}};
          char sense[] = new char[] {'>', '>'};
          double rhs[] = new double[] {4, 1};
          double lb[] = new double[] {0, 0, 0};
          boolean success;
          double sol[] = new double[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 environment
          env.dispose();

        } catch (GRBException e) {
          System.out.println("Error code: " + e.getErrorCode() + ". " +
              e.getMessage());
          e.printStackTrace();
        }
      }
    }

    #!/usr/bin/env python3

    # 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.

    import sys
    import gurobipy as gp
    from gurobipy import GRB

    def dense_optimize(rows, cols, c, Q, A, sense, rhs, lb, ub, vtype, solution):
        model = gp.Model()

        # Add variables to model
        vars = []
        for j in range(cols):
            vars.append(model.addVar(lb=lb[j], ub=ub[j], vtype=vtype[j]))

        # Populate A matrix
        for i in range(rows):
            expr = gp.LinExpr()
            for j in range(cols):
                if A[i][j] != 0:
                    expr += A[i][j] * vars[j]
            model.addLConstr(expr, sense[i], rhs[i])

        # Populate objective
        obj = gp.QuadExpr()
        for i in range(cols):
            for j in range(cols):
                if Q[i][j] != 0:
                    obj += Q[i][j] * vars[i] * vars[j]
        for j in range(cols):
            if c[j] != 0:
                obj += c[j] * vars[j]
        model.setObjective(obj)

        # Solve
        model.optimize()

        # Write model to a file
        model.write("dense.lp")

        if model.status == GRB.OPTIMAL:
            x = model.getAttr("X", vars)
            for i in range(cols):
                solution[i] = x[i]
            return True
        else:
            return False

    # Put model data into dense matrices

    c = [1, 1, 0]
    Q = [[1, 1, 0], [0, 1, 1], [0, 0, 1]]
    A = [[1, 2, 3], [1, 1, 0]]
    sense = [GRB.GREATER_EQUAL, GRB.GREATER_EQUAL]
    rhs = [4, 1]
    lb = [0, 0, 0]
    ub = [GRB.INFINITY, GRB.INFINITY, GRB.INFINITY]
    vtype = [GRB.CONTINUOUS, GRB.CONTINUOUS, GRB.CONTINUOUS]
    sol = [0] * 3

    # Optimize

    success = dense_optimize(2, 3, c, Q, A, sense, rhs, lb, ub, vtype, sol)

    if success:
        print(f"x: {sol[0]:g}, y: {sol[1]:g}, z: {sol[2]:g}")

    ' 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.

    Imports Gurobi

    Class dense_vb

        Protected Shared Function _
          dense_optimize(env As GRBEnv, _
                         rows As Integer, _
                         cols As Integer, _
                         c As Double(), _
                         Q As Double(,), _
                         A As Double(,), _
                         sense As Char(), _
                         rhs As Double(), _
                         lb As Double(), _
                         ub As Double(), _
                         vtype As Char(), _
                         solution As Double()) As Boolean

            Dim success As Boolean = False

            Try
                Dim model As New GRBModel(env)

                ' Add variables to the model

                Dim vars As GRBVar() = model.AddVars(lb, ub, Nothing, vtype, Nothing)

                ' Populate A matrix

                For i As Integer = 0 To rows - 1
                    Dim expr As New GRBLinExpr()
                    For j As Integer = 0 To cols - 1
                        If A(i, j) <> 0 Then
                            expr.AddTerm(A(i, j), vars(j))
                        End If
                    Next
                    model.AddConstr(expr, sense(i), rhs(i), "")
                Next

                ' Populate objective

                Dim obj As New GRBQuadExpr()
                If Q IsNot Nothing Then
                    For i As Integer = 0 To cols - 1
                        For j As Integer = 0 To cols - 1
                            If Q(i, j) <> 0 Then
                                obj.AddTerm(Q(i, j), vars(i), vars(j))
                            End If
                        Next
                    Next
                    For j As Integer = 0 To cols - 1
                        If c(j) <> 0 Then
                            obj.AddTerm(c(j), vars(j))
                        End If
                    Next
                    model.SetObjective(obj)
                End If

                ' Solve model

                model.Optimize()

                ' Extract solution

                If model.Status = GRB.Status.OPTIMAL Then
                    success = True

                    For j As Integer = 0 To cols - 1
                        solution(j) = vars(j).X
                    Next
                End If

                model.Dispose()

            Catch e As GRBException
                Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
            End Try

            Return success
        End Function

        Public Shared Sub Main(args As String())
            Try
                Dim env As New GRBEnv()

                Dim c As Double() = New Double() {1, 1, 0}
                Dim Q As Double(,) = New Double(,) {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}}
                Dim A As Double(,) = New Double(,) {{1, 2, 3}, {1, 1, 0}}
                Dim sense As Char() = New Char() {">"C, ">"C}
                Dim rhs As Double() = New Double() {4, 1}
                Dim lb As Double() = New Double() {0, 0, 0}
                Dim success As Boolean
                Dim sol As Double() = New Double(2) {}

                success = dense_optimize(env, 2, 3, c, Q, A, sense, rhs, lb, Nothing, _
                                         Nothing, sol)

                If success Then
                    Console.WriteLine("x: " & sol(0) & ", y: " & sol(1) & ", z: " & sol(2))
                End If

                ' Dispose of environment

                env.Dispose()

            Catch e As GRBException
                Console.WriteLine("Error code: " & e.ErrorCode & ". " & e.Message)
            End Try

        End Sub
    End Class

Help and Feedback

Press `/` or click to search this documentation | Gurobi website | Gurobi community forum
Go to other Gurobi documentation | Gurobi download | Contact support