【问题标题】:Eliminate numbers in cell arrays recursively递归消除元胞数组中的数字
【发布时间】:2015-05-20 22:21:24
【问题描述】:

我一直在做作业(这只是一部分),我必须递归处理单元格数组,例如:

{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 的数组,它也会崩溃。

【问题讨论】:

    标签: arrays matlab cell-array


    【解决方案1】:

    需要递归调用函数,

    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
    

    【讨论】:

    • 怎么没有意义?我想不出没有循环的方法。
    • 变量list 始终只包含两个元素:数据list{1} 和尾部列表list{2}
    • 这可能是变量列表的一个具体例子,我们不知道。
    • 这是 Haskell、Prolog 和可能的其他语言实现列表的方式。由于 OP 在他的问题中使用了这个确切的结构{1,{2,{5,{6,{}}}}},我假设作业也可能使用这个约定。 (他的错误实现也采用了这种确切的格式。)
    【解决方案2】:

    您从列表中删除第一个元素的部分不正确。

    代替

    list(1)=list{2}(1);
    list(2)=list{2}(2);
    list{2}=filter_list(list{2},p);
    

    你应该简单地使用:

    list = filter_list(list{2},p);
    

    如果您采用整体方法可能会更清楚:

    function list = filter_list(list, p)
    if ~isempty(list)
        if p(list{1}) 
            list = {list{1}, filter_list(list{2}, p)}; %// Keep head of list
        else
            list = filter_list(list{2}, p);            %// Only keep filtered tail
        end
    end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      • 2013-10-27
      相关资源
      最近更新 更多