9
$\begingroup$

Let $x \in \mathbb{R}^n$ be an optimization variable. Now, at a constraint, I would like to count how many times a value, say $2$, appears in $x$ decision.

I think we can have a binary variable $y_i$ indicating whether $x_i =2$. So, $x_i - 2 = 0$ should imply $y_i = 1$. But, anything except $0$ should imply $y_i = 0$. What is the easiest way for this?

Note: since we can subtract $2$ from each element of $x$, we are interested in the number of zeros in $x-2$. So, 'the number of zeros in a decision vector' constraint will also make it.

We may assume $x$ consists of elements $x_i< M$ for some constant $M$

$\endgroup$
  • 3
    $\begingroup$ You can't really check for exact inequality. If you're willing to allow a small tolerance around 2 (say), then the approach described here might work to set your $y_i$ variables. $\endgroup$ – LarrySnyder610 Sep 12 '19 at 2:07
  • $\begingroup$ I think there should be something with demeaning $x$ and then taking the absolute values... But, not sure. $\endgroup$ – independentvariable Sep 12 '19 at 2:10
  • $\begingroup$ What do you mean "demeaning" $x$? $\endgroup$ – LarrySnyder610 Sep 12 '19 at 2:19
  • $\begingroup$ $x_i - 2$ for all $i$. Now I tried to use Yalmip's iff command. Apparently, this works. But idk how $\endgroup$ – independentvariable Sep 12 '19 at 2:23
  • 1
    $\begingroup$ Just to clarify, what you want is to define a variable $y$ associated with an $x$ such that $y=1$ iff $x=2$ (otherwise $y=0$)? $\endgroup$ – Nikos Kazazakis Sep 12 '19 at 11:09
8
$\begingroup$

As LarrySnyder610 said, you cannot do exactly what you want when $x_i$ is continuous. (You can if it is an integer variable.) I discussed how to model this particular issue here: Flagging a Specific Variable Value.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.