Suppose we want 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. The following code 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, we can build the expression \( a^\top X b \) 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)))

The first version of the Python matrix API was included in the release of Gurobi 9.0. The developers are continually working on behavior like this to improve the usability of the matrix API.

### Further information