Matlab中删除超集的问题

eoxn13cs  于 2022-12-13  发布在  Matlab
关注(0)|答案(1)|浏览(168)

我有一个数据集,其中包含我想要删除的超集,其子集如下所示:

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]

如输出所示,仍然存在应当被去除的超集,即,x1M0N1x,因为x1M1N1x包含作为其子集的x1M2N1x,x1M3N1x应当被去除,因为x1M4N1x包含x1M5N1x,并且x1M6N1x包含x1M7N1x,以及x1M8N1x也应当被删除,因为x1M9N1x包含子集x1M10N1x。
预期输出为

a{1} = [5] 
a{2} = [1]
a{3} = [11]
a{4} = [16]
a{5} = [14]

有人能帮我得到准确的结果吗?

7gcisfzg

7gcisfzg1#

我认为你需要使用下面的三角形部分,而不是上面的:

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)

顺便说一下,运行双循环可能比上面的矩阵运算更容易。

相关问题