Finding (multiset) difference between two arrays

后端 未结 5 560
星月不相逢
星月不相逢 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条回答
  •  Happy的楠姐
    2021-01-19 03:10

    Still another approach using the histc function:

    A = [2, 4, 6, 4, 3, 3, 1, 5, 5, 5];
    B = [2, 3, 5, 5];
    
    uA  = unique(A);
    hca = histc(A,uA); 
    hcb = histc(B,uA);
    res = repelem(uA,hca-hcb)
    

    We simply calculate the number of repeated elements for each vectors according to the unique value of vector A, then we use repelem to create the result.

    This solution do not preserve the initial order but it don't seems to be a problem for you.

    I use histc for Octave compatibility, but this function is deprecated so you can also use histcounts

提交回复
热议问题