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")