Skip to main content

Trying to define a variable as the index in another (vector) variable (MATLAB,YALMIP)

Answered

Comments

3 comments

  • Riley Clement
    • Gurobi Staff

    Hi Pira,

    Say you have binary variables \(a_1, \ldots, a_n\) and integer variable \(b\), then introduce binary variables \(x_1, \ldots, x_n\) and the following constraints.

    \begin{eqnarray}
    \sum_{i=1}^nx_i & \leq & 1\\
    x_i & \leq & a_i, \quad \forall i \in \{1,\ldots,n\}\\
    \sum_{j=1}^i x_j & \geq & a_i, \quad \forall i \in \{1,\ldots,n\}\\
    b & = & \sum_{i=1}^nix_i
    \end{eqnarray}

    The \(x\) variable corresponding to the leading 1, will be 1, all else will be 0.

    An example:

    \begin{eqnarray}
    && a = (0,0,1,0,1,1)\\
    && x = (0,0,1,0,0,0)\\
    && b = 1\cdot0 + 2\cdot0 + 1\cdot3 + 0\cdot4 + .... = 3\\
    \end{eqnarray}

    If \(a\) is all zero then \(b\) will be zero.

    - Riley

    0
  • Pira Perry
    • Gurobi-versary
    • First Comment
    • First Question

    Hi Riley,

    Thanks for your immediate reply.
    Seems like there's no existed function to express this constraint, but it's nice to use the index i to weight and sum. I will try it.

    Thanks again and best regards.
    Pira

    0
  • Riley Clement
    • Gurobi Staff

    Hi Pira,

    No problem, another formulation to try also:

    Introduce binary variables \(x_1, \ldots, x_n\) and the following constraints.

    \begin{eqnarray}
    a_i & \leq & x_i, \quad \forall i \in \{1,\ldots,n\}\\
    x_i & \leq & x_{i+1}, \quad \forall i \in \{1,\ldots,n-1\}\\
    \sum_{j=1}^ia_j & \geq & x_i \quad \forall i \in \{1,\ldots,n\}\\
    b & = & n+1 - \sum_{i=1}^nx_i
    \end{eqnarray}

    An example:

    \begin{eqnarray}
    && a = (0,0,1,0,1,1)\\
    && x = (0,0,1,1,1,1)\\
    && b = 7 - \sum_ix_i = 3\\
    \end{eqnarray}

    If \(a\) is all zero then \(b\) will be \(n+1\).

    I'm not sure which approach is best without running tests, but feel free to share if you find out.

    - Riley

    0

Please sign in to leave a comment.