如何在比较后从单元格数组中删除元素而不会导致单元格数组变空?

时间:2015-03-28 14:37:20

标签: arrays matlab set cell-array

我创建了一维数组,它显示了单词以及它们出现的句子。在那之后,我采用交叉点来显示哪个单词出现在句子中的每个其他剩余单词:

OccursTogether = cell(length(Out1));
for ii=1:length(Out1)
for jj=ii+1:length(Out1)
OccursTogether{ii,jj} = intersect(Out1{ii},Out1{jj});
end
end
celldisp(OccursTogether)

上述代码的输出如下:

OccursTogether{1,1} =

 4 11 14

OccursTogether{1,2} =

 1
OccursTogether{1,3} =

 []
OccursTogether{1,4} =

 1 4 8 14 15 19 20 22

OccursTogether{1,5} =

 4 11

我想检查单个元素,如果它的删除不会导致空集,则应删除它,但如果删除它会导致空集,则不应删除它。

例如:

step1:{1,1}{1,5}删除4,它不会为空,因此应删除4。

step2:{1,1}{1,4}删除14,它不会为空,因此也应删除14。

step3:如果我从{1,1}{1,5}删除11,则会导致空集,因为在4中删除了14step 1 step 2所以不应删除它。

应该对数组的所有单元格执行元素删除操作。OccursTogether被声明为1D单元格数组。

我如何编码以对所有OccursTogether单元阵列位置进行比较和删除?

1 个答案:

答案 0 :(得分:1)

使用以下内容,其中C代表您的OccursTogether单元格(更短,因此更容易阅读此答案)。代码中的注释解释了相应行的内容。

C = cell(3,2);

C{1,1} = [4 11 14];
C{2,1} = 1;
C{2,2} = [1 4 8 14 15 19 20 22];
C{3,2} = [4 11];
celldisp(C)

C = cellfun(@unique, C, 'UniformOutput', false); % remove duplicates from elements of C

numsInCell = unique([C{:}]); % numbers in cell, sorted

for n = numsInCell % loop over numbers in cell
    lSetIs1 = cellfun(@numel,C) == 1; % length of set is 1
    nInSet = cellfun(@(set) any(set==n), C); % set contains n
    nIsUnique = sum(nInSet(:))==1; % n occurs once
    condition = ~nIsUnique & ~any(nInSet(:) & lSetIs1(:)); % set neither contains n and has length of 1, nor n is unique
    if condition % if false for all sets...
        C = cellfun(@(set) set(set~=n), C, 'UniformOutput', false); % ... then remove n from all sets
    end
end

celldisp(C)

注意我在for循环的行中使用逻辑索引,从C = cellfun(...开始,这为for的元素提供了额外的C循环。 MATLAB函数cellfun在第一个参数中对第二个参数中单元格的元素执行函数句柄。这是一个非常有用的工具,可以防止使用许多for - 循环甚至一些if语句。