### If you are using Gurobi 10

Operations on 2D MVar work natively, following the dimensionality conventions of numpy. For example, let \( a \in \mathbb{R}^m \), let \(b \in \mathbb{R}^n \), and let \(X\) be an \( m \times n \) MVar object. We can model the expression \( a^\top X b \) as follows:

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)

### If you are using Gurobi 9.x

In Gurobi version 9.x, operations with 2-D MVar objects were largely unsupported. Attempting to construct the expression \( a^\top X b \) with the above code results in `GurobiError: Variable is not a 1D MVar object`:

Matrix linear expressions could only be constructed from 1-D MVar objects. For example, the expression \( a^\top X b \) is built by slicing the 2-D \( X \) matrix variable down to single dimensions, then accumulating the result:

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 an array and an MVar with the matrix-friendly Python API?

## Comments

0 comments

Please sign in to leave a comment.