Number of times the rows of a small matrix appear amongst the rows of a larger matrix, vectorization
1 view (last 30 days)
Show older comments
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!
2 Comments
Accepted Answer
madhan ravi
on 13 Jun 2020
Edited: madhan ravi
on 13 Jun 2020
[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!
0 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!