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!
  2 件のコメント
madhan ravi
madhan ravi 2020 年 6 月 13 日
You forgot to post the expected result.
Adri
Adri 2020 年 6 月 13 日
For the matrices in the example, the result should be
result =
2
3
0

サインインしてコメントする。

採用された回答

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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by