Search code examples
stringmatlabcellintersect

Matlab,alphabetic order of the intersect result


I use intersect function to find common strings in two cell arrays A and B ([~,idx]=intersect(A,B))and save indexes in idx. Then I extract the common strings by A(idx). I see that the results are sorted in alphabetic order. I want to sort them as they sorted in A, Why these strings sorted in alphabetic order?

Thanks.


Solution

  • As explained in the documentation, you can add the option setOrder='stable' to preserve the order of the elements:

    [C,ia,ib] = intersect(A,B,'stable');
    

    You don't even have to capture the indices (unless used elsewhere), as the example shows:

    C = intersect([7 0 5],[7 1 5],'stable')
    returns
    C = [7 5]

    and

    A='hgfedcba';
    B='hac';
    [~,ia]=intersect(A,B,'stable');
    ia'
    
    >   1   6   8
    
    A(ia)
    
    >   hca
    

    For Matlab R2011b and older:

    If your matlab version doesn't support the 'stable' option, you can just use sort on the indices:

    [~,ia]=intersect(A,B);
    ia=sort(ia);
    A(ia)
    
    >   1   6   8
    
    A(sort(ia))
    

    Duplicates

    If they're duplicates in A, intersect will only find them once. ismember might be better suited if you want to find all of the duplicates:

    A='hhggffeeddccbbaa';
    B='hac';
    [~,ia]=intersect(A,B);
    ia=sort(ia);
    A(ia)
    
    >   hca
    
    [~,loc] = ismember(A,B);
    ia=find(loc~=0); % because you want the indices (logical indexing is also an option of course)
    A(ia)
    
    >   hhccaa