How to efficiently find index of matrix elements in another matrix

manoj kandukuri
manoj kandukuri
Altair Employee
edited May 2021 in Community Q&A

Hello,

I have a matrix A of size 350000X1 and i want to find index of A in matrix B of size 900000 X 1. I used "Intersect" as below and it takes ~5 mins to get the result. Is there an efficient way to achieve this any faster? 

[x,y,z] = intersect(A,B);

 

thanks,
Manoj kandukuri

Tagged:

Answers

  • Roberta Varela_20843
    Roberta Varela_20843 New Altair Community Member
    edited May 2021

    @Manoj Kandukuri,

    Are you willing to store only x results or do you also need y and z? Because in case you need only x, this solution is much faster:

    x3 = unique(A(ismember(A,B)))

    As a comparison, if you run these commands, which I created to replicate your scenario:

    image

    It is around 4 times faster with the second approach:

    Elapsed time is 5.662 seconds.

    Elapsed time is 1.344 seconds.

    Regards,

    Roberta

  • manoj kandukuri
    manoj kandukuri
    Altair Employee
    edited May 2021

    Thank you Roberta,

    I need "y" & "z" (which consists of index of each element of A  in matrix B). I need to parse these index to readcae command as requests.

    thanks,

    manoj kandukuri

     

     

  • Roberta Varela_20843
    Roberta Varela_20843 New Altair Community Member
    edited May 2021

    @Manoj Kandukuri,

    What about adding these 2 commands after what I already suggested?

    [bool,y2] = ismember(x2,A);
    [bool,z2] = ismember(x2,B);

    Results are the same (y is the original approach you shared and y2 is the new one):

    image

    It is still more than 2 times faster:

    Elapsed time is 8.715 seconds.

    Elapsed time is 3.456 seconds.

    Regards,

    Roberta

  • Roberta Varela_20843
    Roberta Varela_20843 New Altair Community Member
    edited May 2021

    PS: I wrote x2 in my latest commands, but I guess it should have been x3, to be aligned with my previous comment!

    Roberta