Yebac
Yebac

Reputation: 179

How can I count the number of positions where both my vectors have a given value?

Say A and B are 2 vectors where length(A) = length(B). All elements of A and B are either 0 or 1. How can I count in 1 line the number of positions where both vectors have the value 1?

Upvotes: 1

Views: 128

Answers (3)

abcd
abcd

Reputation: 42225

Just to add to the list of solutions, you can also do the dot-product, which will give you the answer:

C=A'*B;            %'# here I've assumed A & B are both column vectors

This is also by far the fastest of the solutions posted.

Timing test

A=round(rand(1e5,1));
B=round(rand(1e5,1));

Dot-product

tic;for i=1:1e4;A'*B;end;toc                                                       %'SO formatting
Elapsed time is 0.621839 seconds.

nnz

tic;for i=1:1e4;nnz(A&B);end;toc
Elapsed time is 14.572747 seconds.

sum(bitand())

tic;for i=1:1e4;sum(bitand(A,B));end;toc
Elapsed time is 64.111025 seconds.

Upvotes: 3

Jonas
Jonas

Reputation: 74940

One of many solutions, using nnz instead of sum to find the number of non-zero elements:

nnz(A&B)

Upvotes: 1

AVH
AVH

Reputation: 11516

This should do it:

sum(bitand(A, B))

Upvotes: 0

Related Questions