How do I find rows that match a list of vectors without using a loop?

조회 수: 4 (최근 30일)
Let's say I have a list of length 2 vectors that can occur, which I put in a matrix as rows:
possible = [1 2; 1 3; 1 4; 1 5;
2 1; 2 3; 2 4; 2 5;
3 1; 3 2; 3 4; 3 5;
4 1; 4 2; 4 3; 4 5;
5 1; 5 2; 5 3; 5 4];
and I have a set of observed vectors of length 2 that did occur:
observed = [1 3;
1 5;
4 2;
4 3;
3 2;
4 2]; % ... and so on
I need to go through the rows in the list of possible length 2 vectors, and get the index of where each row occurs in observed, like this:
for c = 1:size(possible, 1)
[~, index{c}] = ismember(observed, possible(c,:),'rows');
end
Whilst this approach does work, it proves to be very slow for my approach, as I have many observed matrices to run through, and many possible matrices to run through as well.
Is there a way of making this more efficient? Perhaps by using something other than a for loop?

채택된 답변

Matt J
Matt J 2023년 4월 13일
편집: Matt J 2023년 4월 13일
It would be advisable to obtain the indices as a logical matrix rather than as subscripts. This can be done looplessly with pdist2 as below.
observed = [1 3;
1 5;
4 2;
4 3;
3 2;
4 2]; % ... and so on
possible = [1 2; 1 3; 1 4; 1 5;
2 1; 2 3; 2 4; 2 5;
3 1; 3 2; 3 4; 3 5;
4 1; 4 2; 4 3; 4 5;
5 1; 5 2; 5 3; 5 4];
index=pdist2(observed,possible)==0
index = 6×20 logical array
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
  댓글 수: 3
David Haydock
David Haydock 2023년 4월 13일
Thank you so much. I just implemented it into my code and I am not joking when I say it will have saved me a day of processing time. Thank you so much.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by