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
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
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
Post is closed for comments.
Comments
2 comments