如何在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
答案 0 :(得分:2)
以下是使用find
和cell2mat
的方式。
我们的想法是将每个单元转换为数字矩阵,并使用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);