필터 지우기
필터 지우기

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