Skip to main content

Passing variables to a function for evaluation then returning the result for optimization

Answered

Comments

1 comment

  • Jaromił Najman
    Gurobi Staff Gurobi Staff

    Hi Marcus,

    You can pass optimization variables as arguments to other functions. However, note that you cannot access their values before an optimization run has been performed. It is because the Var object does not have any value. The parameter fields of a Var object get filled after/during an optimization run and can be accessed via its attributes.

    A simple function to construct some objective function would be:

    import gurobipy as gp
    from gurobipy import GRB

    def myfunc(x,I):
      lexpr = gp.quicksum((i+1) * x[i] for i in range(I))
      return lexpr

    m = gp.Model("test")
    x = m.addVars(5)
    m.setObjective(myfunc(x,5))

    In the above function \(\texttt{myfunc}\) computes the LinExpr object \(1 x_0 + 2 x_1 + 3 x_2 + 4 x_3 + 5 x_4\).

    Best regards, 
    Jaromił

    0

Please sign in to leave a comment.