Tim
Tim

Reputation: 99488

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

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!

Upvotes: 5

Views: 8983

Answers (1)

Jonas
Jonas

Reputation: 74940

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

Upvotes: 15

Related Questions