Using the following code to form the linear expression \( a^\top X b \), where \( a \in \mathbb{R}^m \), \(b \in \mathbb{R}^n \), and \(X\) is an \( m \times n \) MVar object, results in a Variable is not a 1D MVar object error GurobiError:
import gurobipy as gp
import numpy as np
model = gp.Model()
X = model.addMVar((3,4))
a = np.random.rand(3)
b = np.random.rand(4)
model.setObjective(a @ X @ b) # error!
Currently, matrix linear expressions can only be constructed from 1-D MVar objects. Instead, the expression \( a^\top X b \) can be built by appropriately slicing the 2-D \( X \) matrix variable:
import gurobipy as gp
import numpy as np
model = gp.Model()
X = model.addMVar((3,4))
a = np.random.rand(3)
b = np.random.rand(4)
model.setObjective(sum(b[j] * a @ X[:, j] for j in range(4)))
Note: Gurobi 9.0 introduced the first version of the Python matrix API. The developers are continually working to improve the usability of the matrix API.
Further information
- How do I multiply two MLinExpr objects together with the matrix-friendly Python API?
- How do I pointwise multiply a numpy vector with a (1,) MVar with the matrix-friendly Python API?
- How do I pointwise multiply two MVars with the matrix-friendly Python API?
- How do I pointwise multiply a scalar vector and an MVar with the matrix-friendly Python API?