nnz overloads nnz operator
N = nnz(X)
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 enable big-M reformulations.
A = randn(20,10); b = randn(20,1)*20; x = intvar(10,1); e = b-A*x; F = [nnz(x) <= 5, -100 <= x <= 100]; optimize(F,e'*e);
As an illustration of cardinality constraints on constraints, we add the constraint that at least 2 of the integer variables are positive.
F = [nnz(x) <= 5, -100 <= x <= 100]; F = F + [nnz(x>=1) >= 2]; optimize(F,e'*e);
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 = [nnz(x) <= 5, -100 <= x <= 100]; F = F + [nnz(x>=0.5) >= 2]; optimize(F,e'*e);
As a final example, we constrain a variable \(x\) to be outside a polytope \(Ax\leq b\).
F = [nnz(A*x <= b) <= length(b) - 1]
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.