Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient ways to check and count zero or one in a vector of logical variables

Tags:

matlab

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!

like image 479
Tim Avatar asked Nov 17 '10 22:11

Tim


People also ask

How do you know if a vector has only one element?

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 .

What is a logical vector in R?

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.


1 Answers

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

like image 73
Jonas Avatar answered Oct 10 '22 07:10

Jonas