MATLAB: How to find which elements for each row of matrix B (NxM) are contained in matrix A (NxK), in their corresponding row n using vectorization

containedismemberspeedvectorization

How to find which elements for each row of matrix B (NxM) are contained in matrix A (NxK), in their corresponding row n?
Toy example:
A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
B = [0 7 9 1 8; 1 15 5 15 4; 1 2 20 5 9]
B =
0 7 9 1 8
1 15 5 15 4
1 2 20 5 9
Which elements of B are contained in A (restricted to their corresponding row?): The answer should be a matrix C of same dimensions as B (NxM)
C =
0 0 0 1 0
0 0 1 0 1
0 0 0 0 1
For each column vector of matrix B, it should check if it is contained in A, but only row-wise. For instance, although B(2,1)=1 is contained in A(1,1), they belong to different rows (row 2 vs row 1).
The only solution I have is to use a sum inside a for loop:
C = [];
for i = 1:size(b, 2)
C = [C sum(b(:, i) == a, 2)];
end
C
C =
0 0 0 1 0
0 0 1 0 1
0 0 0 0 1
However, for very big matrices this is very slow. Is there a way I can vectorize this?
PS: because of a warning ("warning: mx_el_eq: automatic broadcasting operation applied"), I had started using sum(bsxfun(@eq, B(:, 4), A), 2) instead of sum(B(:, i) == A, 2), but running a small tic toc experiment it seems that the latter form without bsxfun runs faster and therefore is preferred?

Best Answer

No loops are required.
Method one: permute
>> any(bsxfun(@eq,B,permute(A,[1,3,2])),3)
ans =
0 0 0 1 0
0 0 1 0 1
0 0 0 0 1
Method two: reshape
>> any(bsxfun(@eq,B,reshape(A,size(A,1),1,[])),3)
ans =
0 0 0 1 0
0 0 1 0 1
0 0 0 0 1