Skip to main content

Variable with different indices

Answered

Comments

1 comment

  • Eli Towle
    • Gurobi Staff

    It looks to me like the indexing of \( p \) in the objective function is consistent with the indexing of \( p \) in the constraints. Namely, in the objective function, \( p \) is indexed by a single element of \( F \). However, that single index is \(\bar{f}_{r,c}\), meaning different combinations of \( c \in C \) and \( r \in R\) could correspond to different elements of \( F \).

    To translate this into code, you would need to define the dictionary \( \bar{f} \) that maps \( r \in R \) and \( c \in C \) to an element of \( F \). As long as your \( p \) variables are indexed by \( F \), you can then index \( p \) by \( \bar{f}_{r,c} \in F\). Below is a short Python script that shows one way to approach this.

    import gurobipy as gp

    R = [0, 1, 2, 3, 4]
    C = [0, 1, 2]

    # F = [0, ..., 14]
    F = list(range(len(R) * len(C)))
    print(f"F = {F}")

    # fbar maps each (r, c) pair an index of F
    fbar = {(r, c): len(C) * r + c for r in R for c in C}
    print(f"fbar = {fbar}")

    m = gp.Model()

    # Create p variables, indexed by F
    p = m.addVars(F, name="p")
    m.update()
    print(f"p = {p}")

    for r in R:
    for c in C:
    print(
    f"r={r}, c={c}: fbar[r,c]={fbar[r,c]}, p[fbar[r,c]] = {p[fbar[r,c]]}"
    )

     

    0

Please sign in to leave a comment.