This section includes source code for all of the Gurobi matrix examples.The same source code can be found in theexamples directory of theGurobi distribution.
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# This example formulates and solves the following simple MIP model# using the matrix API:# maximize# x + y + 2 z# subject to# x + 2 y + 3 z <= 4# x + y >= 1# x, y, z binaryimportgurobipyasgpfromgurobipyimportGRBimportnumpyasnpimportscipy.sparseassptry:# Create a new modelm=gp.Model("matrix1")# Create variablesx=m.addMVar(shape=3,vtype=GRB.BINARY,name="x")# Set objectiveobj=np.array([1.0,1.0,2.0])m.setObjective(obj@x,GRB.MAXIMIZE)# Build (sparse) constraint matrixval=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))# Build rhs vectorrhs=np.array([4.0,-1.0])# Add constraintsm.addConstr(A@x<=rhs,name="c")# Optimize modelm.optimize()print(x.X)print(f"Obj:{m.ObjVal:g}")exceptgp.GurobiErrorase:print(f"Error code{e.errno}:{e}")exceptAttributeError:print("Encountered an attribute error")
#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# This example uses the matrix friendly API to formulate the n-queens# problem; it maximizes the number queens placed on an n x n# chessboard without threatening each other.## This example demonstrates slicing on MVar objects.importnumpyasnpimportgurobipyasgpfromgurobipyimportGRBn=8m=gp.Model("nqueens")# n-by-n binary variables; x[i, j] decides whether a queen is placed at# position (i, j)x=m.addMVar((n,n),vtype=GRB.BINARY,name="x")# Maximize the number of placed queensm.setObjective(x.sum(),GRB.MAXIMIZE)# At most one queen per row; this adds n linear constraintsm.addConstr(x.sum(axis=1)<=1,name="row")# At most one queen per column; this adds n linear constraintsm.addConstr(x.sum(axis=0)<=1,name="col")foriinrange(-n+1,n):# At most one queen on diagonal im.addConstr(x.diagonal(i).sum()<=1,name=f"diag{i:d}")# At most one queen on anti-diagonal im.addConstr(x[:,::-1].diagonal(i).sum()<=1,name=f"adiag{i:d}")# Solve the problemm.optimize()print(x.X)print(f"Queens placed:{m.ObjVal:.0f}")
Help and Feedback