Search code examples
arraysmatlabmatrixoptimization

Alternative to find(ismember) to find the position indices in an array


I'm having trouble to modify my code in an efficient way. I have a table of indices, say

table_of_indices=[1,2; 2,3; 3,1; 1,3; 11,8];
     

and take some specific elements in that table

E=[1,3;1,2];

Is there a smart way to find the positions of the elements of E in my table?

For now, I'm using

pos=find(ismember(table_of_indices, E, 'rows'));

but this is obviously super slow for a large table. Note that in my example, the code indeed returns 1 and 4.

I've found this question Faster alternatives to ismember in Matlab when index positions are needed? but I couldn't manage to translate that solution to my problem. Thanks for the help!


Solution

  • Here's another way:

    pos = find(any(all(table_of_indices==permute(E, [3 2 1]), 2), 3));
    

    I initially doubted this would be faster than the original approach using ismember, but the original poster @Spida says that, in their use case, this is indeed significantly faster.