Count if a vector has at list one element greater than zero
31 views (last 30 days)
Hello everyone, I'm looking for a way to update a count if a vector has at least one element greater than zero.
I mean for example:
%check if v has at least one element greater than zero, if yes
Jorg Woehl on 5 Mar 2021
Edited: Jorg Woehl on 6 Mar 2021
count = sum(v>0)
The expression v>0 creates a logical array of 1s and 0s, with a 1 for every element of v that is greater than zero. Summing all values in the logical array therefore gives the total number of elements greater than zero.
(By the way, the rand function only generates positive numbers between 0 and 1, so to create random numbers between -1 and 1, you would use 1-2*rand.)