Sum of logical vector


(Nora) #1

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.


(Mark L. Stone) #2
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 .


(Nora) #3

Thank you for your answer.

actually this is my first time using cvx and I did not understand the pdf in the link quit will. What I need is to maximize the non zero element of a vector I and I couldnt find something similar.

Also, I don’t see how the question in the link related to my problem.

sorry for bothering you but I couldn’t figure it out on my own


(Mark L. Stone) #4

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.

You might also want to read https://orinanobworld.blogspot.com/2018/09/choosing-big-m-values.html in order to better understand Big M.