Search code examples
arraysmatlabfindcompareindices

matlab: finding indices of values common for two matrices


I have a simple question.

lets say we have two arrays:

data = [1 1 2 2 2 2 3 3 3 4 4 4 4 4 5 5 5 5 6 6 6];
A = [1 3 6];

I want to have indices of values from data which are equal to any value from A.

i.e. answer for that will be: 1, 2, 7, 8, 9, 19, 20, 21

How to do it without using for loop and scanning each value from A one by one..? Thanks! Art.


Solution

  • This will do exactly that:

    inds = find(ismember(data, A))
    

    the function ismember will find all elements in data that are in A. The second output of ismember could also be useful:

    >> [~, b] = ismember(data, A))
    ans = 
        1 1 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 3 3 3
    

    where the 1, 2 and 3 refer to the index into A.