Finding (multiset) difference between two arrays

后端 未结 5 528
星月不相逢
星月不相逢 2021-01-19 02:50

Given arrays (say row vectors) A and B, how do I find an array C such that merging B and C will give A?

For example, given

A = [2, 4, 6, 4, 3, 3, 1         


        
5条回答
  •  情歌与酒
    2021-01-19 03:16

    You can use the second output of ismember to find the indexes where elements of B are in A, and diff to remove duplicates:

    This answer assumes that B is already sorted. If that is not the case, B has to be sorted before executing above solution.

    For the first example:

    A = [2, 4, 6, 4, 3, 3, 1, 5, 5, 5];
    B = [2, 3, 5, 5];
    %B = sort(B); Sort if B is not sorted.
    [~,col] = ismember(B,A);
    indx = find(diff(col)==0);
    col(indx+1) = col(indx)+1;
    A(col) = [];
    C = A;
    
    >>C
    
    4     6     4     3     1     5
    

    For the second example:

    A = [2, 4, 6, 4, 3, 3, 1, 5, 5, 5];
    B = [2, 4, 5, 5];
    %B = sort(B); Sort if B is not sorted.
    [~,col] = ismember(B,A);
    indx = find(diff(col)==0);
    col(indx+1) = col(indx)+1;
    A(col) = [];
    C = A;
    >>C
    
    6     4     3     3     1     5
    

提交回复
热议问题