Skip to main content

How to use if and elif on checking variables?

Answered

Comments

5 comments

  • Eli Towle
    Gurobi Staff Gurobi Staff

    Hi Robert,

    Assuming you want to look for variables whose names start with these letters, you can use the following:

    for v in m.getVars():
        if v.varName.startswith("AA"):
            print("AA")
        elif v.varName.startswith("BB"):
            print("BB")

    However, it's usually possible to avoid searching for variables by name. This can be done by creating a variable from the object returned by the addVar() or addVars() method. For example,

    aa = m.addVars(5, 5, name="AA")

    creates 25 variables with names AA[0,0], AA[0,1], ..., AA[4,4]. In this example, aa is a tupledict object that contains these variables. This object is very useful, because it allows you direct access to the set of "AA" variables:

    for v in aa:
        print(v.varName)

    Thus, the aa tupledict object can be used to build constraints, retrieve variable values, etc. I hope this helps!

    0
  • Han Shih
    Gurobi-versary
    Conversationalist
    Curious

    Hi Eli,

    Thank you very much. It works!

    Best

    Robert

     
    0
  • Han Shih
    Gurobi-versary
    Conversationalist
    Curious

    Hell Eli,

    Can you please help me another question?

    I have a code as below:

    for v in m.getVars():
         print('%s %g' % (v.varName, v.x))

    The varName is 3 by 2 dimension, so x is 3 by 2 dimension too

    When I print, its output is like the following

    A[1,1] 1
    A[1,2] 3
    A[2,1] 2
    A[2,2] 4
    A[3,1] 5
    A[3,2] 3

    is there any way to print a line for each row, like as below:?

    A[1,1] 1   A[1,2] 3
    A[2,1] 2   A[2,2] 4
    A[3,1] 5   A[3,2] 3

    Thank you very much

    Robert

     

     

     

     

     

     

    0
  • Eli Towle
    Gurobi Staff Gurobi Staff

    Hi Robert,

    Assuming your decision variables were added in the following manner:

    A = m.addVars(range(1,4), range(1,3), name="A")

    you can print a line for each row as follows:

    for i in range(1, 4):
        alist = ["%s %g" % (v.varName, v.X) for v in A.select(i, '*')]
        print("\t".join(alist))

    This code snippet uses the select() method of the tupledict object, as well as a Python list comprehension. An example of the output:

    A[1,1] 1        A[1,2] 3   
    A[2,1] 2 A[2,2] 4
    A[3,1] 5 A[3,2] 3

    I hope this helps!

    Eli

     

    0
  • Han Shih
    Gurobi-versary
    Conversationalist
    Curious

    Hi Eli,

    Thank you very much for your help. It seems not easy to write the codes. I will give a try.

    Sincerely,

    Robert

    0

Please sign in to leave a comment.