Search code examples
pythonmatrixmultidimensional-arraylinear-programminggurobi

How to multiply variable matrix by coefficient matrix in Python, using Gurobi


I want to multiply both matrix's below and set as objective for my model:

m = gp.Model("matrix")
x = m.addMVar((9, 9), vtype=GRB.BINARY, name="x")
c = np.random.rand(9,9)

m.setObjective(x @ c, GRB.MINIMIZE)

Here's what am trying to achieve

enter image description here

This gives me following error:

Error code -1: Variable is not a 1D MVar object

How can i solve that? I suppose Gurobi doesn't accept 2D Mvar object multiplication


Solution

  • As already mentioned in the comments, note that the product of two matrices is again a matrix and the evaluated objective needs to be a scalar, so this is probably not what you want to do. According to your picture, your objective is a simple linear expression, not a matrix product. Hence, it's much easier to use Gurobi's algebraic modelling interface, i.e. Vars instead of MVars:

    import gurobipy as gp
    from gurobipy import GRB, quicksum as qsum
    import numpy as np
    
    M, N = 9, 9
    m = gp.Model("matrix")
    x = m.addVars(M, N, vtype="B", name="x")
    c = np.random.rand(M, N)
    
    m.setObjective(qsum(c[i,j]*x[i,j] for i in range(M) for j in range(N)), GRB.MINIMIZE)