我一直在做作业(这只是一部分),我必须递归地使用元胞数组,例如:
{1,{2,{5,{6,{}}}}}
我需要根据属性消除对象,即:
p=@(x)(x<3)
函数名称是filter_list(list,p)
,使用它的结果应该是:
{1,{2,{}}}
代码是:
function [ list ] = filter_list( list,p )
if isempty(list)==1
disp('holo');
return;
else
if p(list{1})==0
disp('hola');
list(1)=list{2}(1);
list(2)=list{2}(2);
list{2}=filter_list(list{2},p);
else
disp('hele')
list{2}=filter_list(list{2},p);
end
end
但是我通过这段代码得到的是:
{1,{2,{6,{}}}}
它仅消除数组中满足以下条件的第一个元素:
p(list{1}) == 0
要求。
我该如何解决这个问题?另外,如果我使用大于 4 的数组,它也会崩溃。
最佳答案
您需要递归调用该函数,
function [ list ] = filter_list( list,p )
for i = numel(list):-1:1 %Go through the cell backwards
if ~iscell(list{i}) %if the cell contains a scalar, vector or matrix
list{i}(~p(list{i})) = []; %if the number does not follow the rule specified by p remove it
if isempty(list{i}) %if there is nothing in the scalar/vector/matrix remove it
list(i) = [];
end
else %if the cell doesn't contain a number call the function again
list{i} = filter_list(list{i}, p);
end
end
end
关于arrays - 递归消除元胞数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30361388/