Trying to define a variable as the index in another (vector) variable (MATLAB,YALMIP)
回答済みHello everyone.
I want to define a decision variable that can indicate the first entry in another variable that is equal to specified value. For example,
a = binvar(4,1); % 4x1 binary variable
b = intvar(1);
I want to add the constraint that let b change with a and indicate the index of first entry in a that is equal to 1, eg. a=(1,1,1,0) => b = 1; a=(0, 1, 1, 0) => b=2; a=(0,0,1,0) => b=3; etc.... The relation between a and b is just like function b=find(a(:) == 1)
Does anyone know how express this constraint in MATLAB? Or any similar constraint? Very much thanks!
-
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 -
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.
Pira0 -
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
サインインしてコメントを残してください。
コメント
3件のコメント