我有一组数据,包括我想删除子集的超集,如下所示:
a{1} = [5]
a{2} = [4 11 14]
a{3} = [1]
a{4} = [5 16]
a{5} = [5]
a{6} = [11 16]
a{7} = [11]
a{8} = [16]
a{9} = [9 14 17]
a{10} = [14]
[ii, jj] = ndgrid(1:numel(a));
s = cellfun(@(x,y) all(ismember(x,y)), a(ii), a(jj));
s = triu(s,1); %// count each pair just once, and remove self-pairs
similarity = a(~any(s,1));
celldisp(similarity)
结果如下:
a{1} = [5]
a{2} = [4 11 14]
a{3} = [1]
a{4} = [11 16]
a{5} = [11]
a{6} = [16]
a{7} = [9 14 17]
a{8} = [14]
因为输出显示仍有超集应该删除,即a{2}
,因为a{5}
包含11
这是其子集,a{4}
应该被移除,因为{{1}由于a{5}
包含子集11
,因此{}包含a{6}
和16
包含a{7}
以及a{8}
也应该被删除。
预期产出
14
任何人都可以帮助如何修复此代码,以便我可以获得准确的结果集。谢谢
答案 0 :(得分:2)
我认为您需要使用下三角形部分而不是上部:
s = tril(s,-1); % instead of s = triu(s,1);
修改强>
仅当子集始终出现在子集之前时,保持下三角部分才有效。这是一个应该始终正常的通用版本。
[ii, jj] = ndgrid(1:numel(a));
s = cellfun(@(x,y) all(ismember(x,y)), a(ii), a(jj));
% Set diagonal to zero.
s = s - diag(diag(s));
% Indicator matrix for sets that are exactly equal.
same = s & s';
% For equal sets keep only the first occurence.
keep = triu(same) | ~same.*s;
% Delete supersets.
similarity = a(~any(keep,1));
celldisp(similarity)
顺便说一下,运行双循环而不是上面的矩阵运算可能更容易。