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?

采纳的回答

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