Printing the values of variables at optimal solution
AnsweredDear Gurobi Team,
I have a operation research' optimization model with certain parameters (fixed values) and some decision variables (variable values that needs to be find out) in my gurobi model my constraints were in style of for loop iterations such as:
and i found the optimal solution but while printing the decision variable values i am using this code:
if model.status == GRB.OPTIMAL:
print("Optimal solution found!")
# Print objective value
print("Objective value:", model.objVal)
# Print decision variable values
for v in model.getVars():
print(v.varName, "=", v.x)
else:
print("Optimal solution not found.")
But it prints all the possible values of all decision variables (that are too much, as attached in photo) but i need only those corresponding values decision variables at which the optimal solution happen.
Please help me out as soon as possible
Thanks in advance

Hi Muhammad,
This is coming from our Gurobi AI Guide:
To filter and print only the nonzero decision variable values in your Gurobi optimization model, you can modify your existing code snippet to check if the value of each variable (
v.x
) is nonzero before printing. This will help in focusing on those variables that actually contribute to the solution.Here's how you can modify your code:
if model.status == GRB.OPTIMAL:
print("Optimal solution found!")
# Print objective value
print("Objective value:", model.objVal)
# Print decision variable values that are nonzero
for v in model.getVars():
if v.x != 0:
print(v.varName, "=", v.x)
else:
print("Optimal solution not found.")This modification adds a simple condition
if v.x != 0
to check the value of each variable before printing. It ensures that only those variables with a significant (nonzero) value are displayed, reducing the clutter in your output and highlighting the active variables at the optimal solution.Note that all the variables in your screenshot contribute to the found optimal solution since they have a nonzero solution value.
Best regards,
Mario0 
hi,
it still generating all the possible values but not the corresponding specific variable values of specific indices that corresponds to that optimal solution
Please give me some other method0 
The found optimal solution is defined by the solution values of all variables in the model. If variables have a nonzero value, then they are part of the optimal solution. If you think too many variables are nonzero and should not be part of a solution, your model formulation is potentially wrong.
For example, if only one of your "Egtineg" variables with first index 1 is allowed to be nonzero, then you have to formulate this requirement with constraints.0
Please sign in to leave a comment.
Comments
3 comments