MATLAB:删除for循环中单元格数组中的元素

时间:2015-03-12 19:29:38

标签: arrays matlab cell-array

如何在for循环中删除单元格数组中的元素?  我有一个名为stated_n {i}的集合,其中i从1变化到n(令n = 5)例如:

stated_n{1} = {3,7,8,9,14,99} 
stated_n{2} = {14,8,19,104,98} 
stated_n{3} = {67,7,8,9,14,11} 
stated_n{4} = {41,76,8,18,14,56} 
stated_n{5} = {65,13,16,9,8,103} 

我希望例如从每个陈述的{i}中删除值k(let k = 8)如何从每个陈述的n中删除8(1:5)

for i=1:N 
    if ismember(k,stated_n{i})
       %remove k from stated_n{i}
       % update stated_n{i} and display it
    end
end

2 个答案:

答案 0 :(得分:2)

以下是使用findcell2mat的方式。

我们的想法是将每个单元转换为数字矩阵,并使用find查找k出现的索引/索引。然后删除这些条目。如果k的实例数超过1个,那也可以。

clear
clc

stated_n{1} = {3,7,8,9,14,99} ;
stated_n{2} = {14,8,19,104,98} ;
stated_n{3} = {67,7,8,9,14,11} ;
stated_n{4} = {41,76,8,18,14,56} ;
stated_n{5} = {65,13,16,9,8,103} ;

N = numel(stated_n);
k = 8;
for i=1:N 

    idx = find(cell2mat(stated_n{i}) == k);

    stated_n{i}(idx) = [];

   %// Display

   stated_n{i}
end

输出:

ans = 

    [3]    [7]    [9]    [14]    [99]


ans = 

    [14]    [19]    [104]    [98]


ans = 

    [67]    [7]    [9]    [14]    [11]


ans = 

    [41]    [76]    [18]    [14]    [56]


ans = 

    [65]    [13]    [16]    [9]    [103]

答案 1 :(得分:1)

删除单个值:

k = 8;
result = cellfun(@(x) x([x{:}]~=k), stated_n, 'uniformoutput', 0);

要删除多个值:

k = [8 4];
result = cellfun(@(x) x(~ismember([x{:}], k)), stated_n, 'uniformoutput', 0);