How do I square a MVar matrix in the objective function?
OngoingHello,
I have several MVars in my model and I would like to square them in the objective function  is this possible? I have Python 3.7 and Gurobi 9.0.
0

Do you mean you want to take the sum of the squared vector values (i.e., \( x_2^2\))? If your matrix is 1D, this is equal to the dot product of the vector with itself:
import gurobipy as gp
m = gp.Model()
x = m.addMVar(3, name='x')
m.setObjective(x @ x)The above code adds the objective \( x_1^2 + x_2^2 + x_3^2 \).
If you have a 2D matrix of variables and you want to calculate the sum of the squared matrix values (\( X_F^2\)), you can iterate over the rows (or columns) of the matrix, summing the squared L2 norms of each matrix slice:
import gurobipy as gp
m = gp.Model()
x = m.addMVar((3,3), name='x')
m.setObjective(sum(x[i, :] @ x[i, :] for i in range(3)))This code adds the objective \( x_{11}^2 + x_{12}^2 + \ldots + x_{33}^2 \).
0
Please sign in to leave a comment.
Comments
1 comment