How do I find rows that match a list of vectors without using a loop?
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Matt J
on 13 Apr 2023
Edited: Matt J
on 13 Apr 2023
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 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!