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

1 次查看(过去 30 天)
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!

采纳的回答

madhan ravi
madhan ravi 2020-6-13
编辑:madhan ravi 2020-6-13
[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 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by