メインコンテンツへスキップ

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

進行中

コメント

2件のコメント

  • 正式なコメント
    Simranjit Kaur
    • Gurobi Staff
    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?.
  • Eli Towle
    • 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 \).

    0

投稿コメントは受け付けていません。