Skip to main content

Get variables indexes




  • Simon Bowly
    Gurobi Staff Gurobi Staff

    Hi José,

    "v.index" will give you the index of the variable in the model. This is different from your indices i and j, as it is an internal Gurobi variable counter.

    I believe what you want is the following (assuming that X is a tupledict created using model.addVars()):

    import collections

    nonzeros_ij = collections.defaultdict(list)
    any_nonzero_i = set()

    for (i, j), v in X.items():
    if v.X > 0.9: # best to allow for numerical tolerances

    "nonzeros_ij" will then be a mapping from an index i to a list of j indices such that X[i,j] is nonzero, while "any_nonzero_i" will be a set of i indices for which X[i,j] is nonzero for some j

  • José Rodrigues

    Hi Simon, 

    Thank you so much for your reply, it is exactly what I was looking for. Nevertheless, there is something still troubling me. 

    I have another variable with the same i and j, HP which is a tupledict created using model.addVars() and this time it's continuous. In this case, besides doing the same as you wrote above, I would also like to get the value of the variable HP, in different lists according to each i at every j. Actually, it's quite similar to getting the nonzeros_ij dictionary that you wrote but this time appending the variable value instead of the j. 


    Could you write down how to do it since I'm not being able to?

    Thank you once more, 

    José Rodrigues 

  • Alison Cozad
    Gurobi Staff Gurobi Staff

    You can retrieve variable values after optimizing with the X variable attribute.  For example, Simon used this attribute check with the variable value \(\texttt{v.X}\) is greater than 0.9 in the conditional \(\texttt{if v.X > 0.9}\).  For more details, see How do I retrieve variable values after optimizing?


Please sign in to leave a comment.