如何删除作为较大元素子集的单元格元素? (Matlab) [英] How to remove cell elements that are a subset of a larger element? (Matlab)

查看:118
本文介绍了如何删除作为较大元素子集的单元格元素? (Matlab)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个单元格,其中的数组在其中列出:

For example, if I have a cell with arrays listed inside:

C = {[1,2,3,4], [3,4], [2], [4,5,6], [4,5], [7]}

我要输出:

D = {[1,2,3,4], [4,5,6], [7]}

最有效的方法是删除已经包含在另一个更大元素中的子元素?

What is the most efficient way to remove cell elements that are already included/subset in another larger element?

我现有的算法遍历每个元素,将其与新单元格列表中的每个元素进行比较,并相应地更新新单元格列表,但是它非常缓慢且效率低下(我原来的单元包含200个以上的数组元素)。

My existing algorithm loops through each element, compares it to each element in the new cell list and updates the new cell list accordingly but it is extremely slow and inefficient (my original cell contains >200 array elements).

推荐答案

这里是一种非常快速的矩阵乘法方法。您可以将 C 转换为稀疏的二进制矩阵 b ,即每个 C 与矩阵的每一行相关。因此,设置第一行的列 [1 2 3 4] 和第二行的列 [3 4] 到1,依此类推。将矩阵与其转置相乘,我们可以找到所有成对的行之间对应元素的数量。

Here is an approach using ,very fast, matrix multiplication. You can convert C to a ,sparse, binary matrix b that each element of C is related to each row of the matrix. So columns [1 2 3 4] of the first row and columns [3 4] of the second row are set to 1 and so on. Multiplying the matrix by its transpose we can find the number of corresponding elements between all pairs of rows. using that information we can find cell elements that are subset of others.

C = {[1,2,3,4], [3,4], [2], [4,5,6], [4,5], [7]};
n = cellfun(@numel,C);      % find length of each element.
v = repelem(1:numel(C),n);  % generate indices for rows of the binary matrix
[~,~,u] = unique([C{:}]);   % generate indices for rows of the binary matrix
b = accumarray([v(:),u(:)],ones(size(v)),[],@max,[],true); % generate the binary matrix
s = b * b.';                % multiply by its transpose
s(1:size(s,1)+1:end) = 0;   % set diagonal elements to 0(we do not need self similarity)
result = C(max(s)<n)        % remove an element if it is a subset and preserve others

这篇关于如何删除作为较大元素子集的单元格元素? (Matlab)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆