Adding constraints to the model

The next step in the example is to add our two linear constraints. This is done by building a sparse matrix that captures the constraint matrix:

    # Build (sparse) constraint matrix
    val = np.array([1.0, 2.0, 3.0, -1.0, -1.0])
    row = np.array([0, 0, 0, 1, 1])
    col = np.array([0, 1, 2, 0, 1])

    A = sp.csr_matrix((val, (row, col)), shape=(2, 3))

The matrix has two rows, one for each constraint, and three columns, one for each variable in our matrix variable. The row and col arrays gives the row and column indices for the 5 non-zero values in the sparse matrix, respectively. The val array gives the numerical values. Note that we multiply the greater-than constraint by <span>$</span>-1<span>$</span> to transform it to a less-than constraint.

We also capture the right-hand side in a NumPy array:

    # Build rhs vector
    rhs = np.array([4.0, -1.0])

We then use the overloaded @ operator to build a linear matrix expression, and then use the overloaded less-than-or-equal operator to add two constraints (one for each row in the matrix expression):

    # Add constraints
    m.addConstr(A @ x <= rhs, name="c")

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.