MATLAB: Number of times the rows of a small matrix appear amongst the rows of a larger matrix, vectorization

findismemberMATLABvectorizationvectorize

Hi!
I need to find the number of times the elements in the rows of a small (Sx2) matrix appear in a larger (Lx4) matrix. I would like to do this in a faster way than doing it with a loop if possible. Some properties the matrices have:
  • both matrices have unique elements on their rows and the order of appeareance doesn't matter
  • an element from the small matrix can always be found at least once in the large matrix
For example:
L = [1 2 3 4
2 5 7 4
2 6 8 3
3 1 2 8
8 6 4 2];
S = [2 1
2 4
5 3];
for kk = 1:length(S(:,1))
times_each_row_appears(kk,1) = nnz(sum(ismember(L,S(kk,:)),2)==2); % sum(_,2) acts along the rows, sum==2 when both elements are found
end
times_each_row_appears
returns
times_each_row_appears =
2
3
0
Does anyone have any suggestion on how to do this faster without a loop, preferrably on matrices with thousands of rows? Thank you!

Best Answer

[m, n] = size(S);
times_each_row_appears = zeros(m,1); %preallocate for speed!
for kk = 1:m
times_each_row_appears(kk,1) = nnz(sum(ismember(L,S(kk,:)),2)==n);
end
Alternative is to use arrayfun(...) but loop is the fastest anyhow!