Skip to main content

How to maximize the determinant of a N by N Matrix variable

Answered

Comments

2 comments

  • Riley Clement
    Gurobi Staff Gurobi Staff

    Hi Yen-Chun,

    If you have a matrix variable x, then you can calculate a determinant with the following code.  You are still encoding a formula for the determinant but using recursion to keep it tidy:

    import gurobipy as gp
    import numpy as np
    
    def det(A):
        v = m.addVar(lb=-float("inf"))
        if A.shape == (2,2):
            m.addConstr(v == A[0,0]*A[1,1]-A[1,0]*A[0,1])
            return v
        expr = gp.QuadExpr()
        cofactor = 1
        for i in range(A.shape[1]):
            cols = [c for c in range(A.shape[1]) if c != i]
            expr += cofactor*A[0,i]*det(A[1:][:,cols])
            cofactor = -cofactor
        m.addConstr(v == expr)
        return v
    
    n = 10 m = gp.Model() x = m.addMVar((n,n), lb=-float("inf"))
    determinant = det(x) # determinant will be a gurobipy.Var

    - Riley

    0
  • Yen-Chun Liu
    First Comment
    First Question

    Thank you!

    0

Please sign in to leave a comment.