How to use the if statement with a variable?
AnsweredCurrently I'm implementing a python code, which is based on Xpress programming
To replicate this, I use:

Nevertheless when I'm programming there's an error:

AttributeError: Index out of range for attribute 'X'
-
Official comment
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?. -
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 -
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 -
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 -
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.
Comments
5 comments