Skip to main content

How to use the if statement with a variable?

Answered

Comments

5 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?.
  • Jaromił Najman
    • Gurobi Staff

    Hi Eduardo,

    The X attribute is available only after the model has been optimized and at least one feasible solution has been found. In general, you cannot evaluate the value of a variable object because it does not have any value. You have to access it via its attributes.

    If the above does not help, could you post a minimal working example to make the issue reproducible?

    Best regards,
    Jaromił

    0
  • İrem Bahtiyar
    • Gurobi-versary
    • First Comment
    • First Question

    Hello, I have the same problem. x_j's are binary variables. But this does not work. how can I use variable in if statement?

    for j in range(T):
    sum8=[]
    sum9=[]
    if m.getattr(x[j])==0 :
    for i in range(C):
    if P[j] in max5[i]:
    sum8.append( 1/(v_0[i]+sum(max5[i]) - P[j]))
    elif P[j] not in max5[i]:
    sum8.append( 1/(v_0[i]+sum(max_sublist[i])))
    y_low0.append(sum8)

    0
  • Jose Vindel
    • Gurobi-versary
    • Thought Leader
    • Investigator

    Hello Irem,

    I am also dealing with binary variables and this is what I do, I use binary variables to solve a knapsack problem where when \(y_s = 0\) is not in the knapsack. And get access to the values using \(model.getVarByName\)

     

    items = # list of items
    M = [i for i in range(len(items))]
    y = model.addVars(M,vtype=GRB.BINARY,name='y')

    # after the model has been solved

    if model.status == GRB.OPTIMAL:
    ys = [model.getVarByName('y[%d]'%j).x for j in M] # gets a list with all your binary solutions
    for i in M:
    if ys[i] <.5:
    print('Item %s not in knapsack'%(item[i]))

    Hope this helps.

    Alex.

    0
  • Jaromił Najman
    • Gurobi Staff

    Hi İrem,

    The line

    if m.getAttr(x[j])==0 :

    should read

    if x[j].X==0 :

    Please note that the X attribute is only available after a previous optimization run found at least one feasible solution point.

    Jose's solution works as well.

    Best regards,
    Jaromił

    0

Post is closed for comments.