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?
댓글 수: 0
채택된 답변
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
댓글 수: 3
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!