In Matlab, given a vector of logicals, for example, v>0 creats a vector of logicals where v is a numerical vector, what are the efficient ways to respectively
(1) check if there is zero(s) in it?
(2) check if there is one(s) in it?
(3) count how many zeros in it?
(4) count how many ones in it?
Thanks!
You can use logical indexing, assuming your vector is v : numel(v(v==1)) returns the number of elements equal to 1 in your vector. In the same way, if you want to check if every value is the same you can use: numel(unique(v)) which returns the number of unique entries of v .
A logical vector is a vector that only contains TRUE and FALSE values. In R, true values are designated with TRUE, and false values with FALSE. When you index a vector with a logical vector, R will return values of the vector for which the indexing vector is TRUE.
Assuming v
is a logical vector
(1) ~all(v)
or any(~v)
is true only if there is at least one zero
(2) any(v)
or ~all(~v)
is true only if there is at least one one
(3) sum(~v)
counts zeros (numel(v)-sum(v)
is faster according to @gnovice)
(4) sum(v)
counts ones
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With