我创建了一维数组,它显示了单词以及它们出现的句子。在那之后,我采用交叉点来显示哪个单词出现在句子中的每个其他剩余单词:
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
中删除了14
和step 1
step 2
所以不应删除它。
应该对数组的所有单元格执行元素删除操作。OccursTogether
被声明为1D单元格数组。
我如何编码以对所有OccursTogether
单元阵列位置进行比较和删除?
答案 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
语句。