Find # nonzero values for variable

Hi there.

I’m trying to solve an optimisation problem where I want to count the number of nonzeros in the x variable in order to attach cost to this.
However, the solution variables for x are never exactly 0, which results in the nnz() function not working.
In cvx the following replacements do not work, does anyone know a way around this?

nnz(abs(x)<1e-6)
nnz(round(x))

To provide an idea of the objective function:

minimize (sum(c'*x) + nnz(x)*300 + sum(-q.*(pb(1)*(y(:,1)) + pb(2)*(y(:,2)) + pb(3)*(y(:,3)))) );

Hopefully someone can help me!

That can probably be handled with introduction of binary variables and use of Big M modeling. I leave the somewhat messy details to you.

Thank you for your response, if I understand correctly, the only way of solving this is by using binary variables? As I want to keep those out of my model, that means removing this part from the equation.

Number of non-zeros is non-convex. Therefore, it will require binary (or integer) variables to handle.

Of course, thank you!