Finding (multiset) difference between two arrays

后端 未结 5 531
星月不相逢
星月不相逢 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

    Here's a vectorized way. Memory-inefficient, mostly for fun:

    tA = sum(triu(bsxfun(@eq, A, A.')), 1);
    tB = sum(triu(bsxfun(@eq, B, B.')), 1);
    result = setdiff([A; tA].', [B; tB].', 'rows', 'stable');
    result = result(:,1).';
    

    The idea is to make each entry unique by tagging it with an occurrence number. The vectors become 2-column matrices, setdiff is applied with the 'rows' option, and then the tags are removed from the result.

提交回复
热议问题