# Sum of logical vector

I am trying to maximize this objective

``````variable x(n) binary
maximize(sum((S*x)>0))
subject to
lowerBound <= x <= upperBound
sum(x) == K
``````

where I want the number of non zero element. This works when I use it with matlab only but it does not work with cvx. instead I get the error:
Error using sum
Invalid data type. First argument must be numeric or logical.

1 Like
``````variable x(n) binary
lowerBound <= x <= upperBound
``````

probably doesnâ€™t make sense because the elements of `x` can only be zero or one due to `x` being declared binary.

I guess rhe link I provided you yesterday wasnâ€™t enough of a hint. So I will direct you to the solution at https://math.stackexchange.com/questions/2500415/how-to-write-if-else-statement-in-linear-programming .

1 Like

In the linked answer, the elements of Sx > 0 play the role of a > b. So declare a binary vector variable `delta(n)`, whose elements are 1 or 0 according to whether the corresponding element of Xx > 0 or not. Then your objective is `maximize(sum(delta))`. The linked answer shows you the constraints you will need to include in your CVX program.