Skip to main content

how to getVar of MVar s?



1 comment

  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    Hi Viviana,

    The getVarByName method only returns a variable if the variable name exactly fits to a model variable. This means that it is not enough for a variable to only have a substring \(\texttt{'val1'}\).

    When you create the variables, you can see that the variable names are expanded through the dimensions of the matrix variables.

    N = 2
    M = 3
    val1 = m.addMVar(N, lb=0.0, ub=GRB.INFINITY, vtype=GRB.CONTINUOUS, name='val1')
    val2 = m.addMVar((N,M), lb=0.0, ub=GRB.INFINITY, vtype=GRB.CONTINUOUS, name='val2')

    > <MVar (2,)>
    > array([<gurobi.Var val1[0]>, <gurobi.Var val1[1]>])
    > <MVar (2, 3)>
    > array([[<gurobi.Var val2[0,0]>, <gurobi.Var val2[0,1]>,
          <gurobi.Var val2[0,2]>],
          [<gurobi.Var val2[1,0]>, <gurobi.Var val2[1,1]>,
          <gurobi.Var val2[1,2]>]])

    To get all these variables by name you have to also provide the indices which are now part of the respective variable names

    res1 = {}
    res2 = {}
    for i in range(N):
    res1[i] = m.getVarByName('val1[%d]'%(i)).X
    for j in range(M):
       res2[i,j] = m.getVarByName('val2[%d,%d]'%(i,j)).X

    If you still have access to the \(\texttt{val1,val2}\) objects after the optimization is complete, you can just use these MVar objects to access the values.

    if m.SolCount > 0: # avoid attribute error if no feasible point is available
    res1 = val1.X
    res2 = val2.X

    On a side note, you are using \(\texttt{m}\) for the Model object and as an index when adding MVars

    val2 = m.addMVar((n,m), ...)

    This can lead to any sort of issues and should definitely be avoided.

    Note that there is an upcoming webinar on the Matrix friendly API where we will discuss all changing and improvements to the Matrix API.

    Best regards, 


Please sign in to leave a comment.