# Binary variable to count appearances

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$$

• 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. – LarrySnyder610 Sep 12 at 2:07
• I think there should be something with demeaning $x$ and then taking the absolute values... But, not sure. – independentvariable Sep 12 at 2:10
• What do you mean "demeaning" $x$? – LarrySnyder610 Sep 12 at 2:19
• $x_i - 2$ for all $i$. Now I tried to use Yalmip's iff command. Apparently, this works. But idk how – independentvariable Sep 12 at 2:23
• 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$)? – nikaza Sep 12 at 11:09

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.