# Constraint on count of variables >0 in JuMP?

I have a model with a control variable as follows:

``````@variable(model, 0 ≤ u[1:(T+1)] ≤ u_max)
``````

I want to constrain the number of elements in `u` greater than 0 to be less than a threshold, `u_nonzero_max`. How can I do this in JuMP?

Here you go:

``````T, u_max, u_non_zero_max = 3, 4.0, 2
model = Model()
@variable(model, 0 <= u[1:(T+1)] <= u_max)
@variable(model, z[1:(T+1)], Bin)
@constraint(model, [t in 1:T+1], u[t] <= u_max * z[t])
@constraint(model, sum(z) <= u_non_zero_max)
``````

Thanks @odow! Unfortunately, my MINLP problem is way slower to fit than my NLP problem. Is there a workaround to do this to avoid binary variables? My searches to find an alternative haven’t amounted to much.

Unfortunately, my MINLP problem is way slower to fit than my NLP problem

This is expected. The M-choose-N-non-zero is quite a nasty constraint.

Is there a workaround to do this to avoid binary variables?

No good ones. Consider the case when `T = 1` and `u_non_zero_max = 1`. There are two decisions variables, and the feasible region is the L formed by the x- and y-axes from `[0, u_max]`. This is the same as a classical complementarity constraint, and you’ve made it harder by increasing the dimension

1 Like