# nnz

Tags:

Updated:

## Syntax

N = nnz(X)


## Examples

The nnz operator can be applied to both sdpvar objects and constraints.

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]