在matlab中进行比较后删除单元数组中任何整数的通用方法?

时间:2015-03-30 11:31:31

标签: arrays matlab cells

这是How to delete element from cell arrays after comparisons without causing cell arrays to get empty?的后续问题,我得到了部分解决方案。以下是代码:

A = cell(2);
A{1} = [2 4];
A{3} = [3 2 0];
A{4} = 1;
celldisp(A) % A contains one 2, an empty cell, a double array and a 1.

AWithout2ButNotEmptied = cellfun(@(x) x( (x~=2) | (numel(x)<2) ), A,'UniformOutput', false);
celldisp(AWithout2ButNotEmptied)

上述代码的输出是:

A{1,1} =
 2 4
A{2,1} =
 []
A{1,2} =
 3     2     0
A{2,2} =
 1
AWithout2ButNotEmptied{1,1} =
 4
AWithout2ButNotEmptied{2,1} =
 []
AWithout2ButNotEmptied{1,2} =
 3     0
AWithout2ButNotEmptied{2,2} =
 1

输出显示A{1,1}等于4并且在删除2后没有清空,因为它的长度小于2(长度为1)。 A{1,2}已删除等于2的元素。 A{2,1}已经为空,保持不变。 A{2,2}的长度为1,但不等于2,因此它保持不变,因此,仅对数字2执行检查是否要删除。

如果不导致任何其他数组变空,我如何更改此代码以从任何单元格元素中删除任何数字x(not only 2)

我想对我的单元格中x(1,...,n)的任何值执行此操作,我不想从单元格数组中删除任何特定数字x

例如:

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

我想要的结果如下;

OccursTogether{1,1} =

 11

OccursTogether{1,2} =

1
OccursTogether{1,3} =

[]
OccursTogether{1,4} =

1 8 15 19 20 22

OccursTogether{1,5} =

 11

您可以看到414从多个单元格中移除,从而产生上述结果。我们无法移除11,因为它会导致{1,1}处的空位置,{1,5}在删除之前应对每个数字x应用相同的检查。

1 个答案:

答案 0 :(得分:1)

我的answer to your previous question现已更新。

我在这里复制了它:


使用以下内容,其中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语句。