Skip to main content

How do I square a MVar matrix in the objective function?



1 comment

  • Eli Towle
    Gurobi Staff Gurobi Staff

    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 \).


Please sign in to leave a comment.