The following code defines a least squares problem with integer variables, with the constraints that at most 5 variables are non-zero. As usual, we add explicit bound constraints to improve the big-M reformulations.
b = randn(20,1)*20;
x = intvar(10,1);
e = b-A*x;
F = [nnz(x) <= 5, -100 <= x <= 100];
As an illustration of cardinality constraints on constraints, we add the constraint that at least 2 of the integer variables are positive.
F = F + [nnz(x>=1) >= 2];
To avoid border-line numerical issues, it is recommended to use the constraint x>=0.5 instead of x>=1 (they model the same constraints due to the integrality anyway)
F = F + [nnz(x>=0.5) >= 2];
As a final example, we constrain a variable x to be outside a polytope Ax<b.
The command should only be applied to integer (or binary) variables. If applied to continuous variables, it has to be kept in mind that it is extremely sensitive to model if a variable is zero or not, when working in floating point numerics and numerical solvers with finite precision.