JohnnyF
JohnnyF

Reputation: 1101

MATLAB-making intersect faster

Let there be two arrays {A,B} of size 1xN

I want to find the number of cases where on the same indices

the condition A(ii)==1 & B(ii)==0 is satisfied.

I tried

casess= intersect( find(A==1),find(B==0 ))

but this is very slow.

I believe this is because intersect checks on every member if it is member of the other group, but I am still looking for the fastest solution to my smaller problem.

Upvotes: 0

Views: 406

Answers (1)

buzjwa
buzjwa

Reputation: 2652

The number of cases where this condition is true can be computed with:

numCases = sum(A == 1 & B == 0);

The expression A == 1 & B == 0 gives a logical array which can be used, for example, to find the indices where the condition is true:

ind = find(A == 1 & B == 0);

or to directly access a matrix with the same size via logical indexing:

C = zeros(size(A));
C(A == 1 & B == 0) = 5;

Upvotes: 5

Related Questions