How do I find rows that match a list of vectors without using a loop?
3 次查看(过去 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
更多回答(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!