【问题标题】:MATLAB: Using cellfun with multi level cell arrayMATLAB:将 cellfun 与多级元胞数组一起使用
【发布时间】:2018-10-27 16:05:00
【问题描述】:

我有一个多级元胞数组。各个级别可以具有不同的大小。我想知道如何将cellfun 应用到最低级别。想象一下下面的多级元胞数组:

a = {randi(10,5,1), randi(5,5,1)}
b = randi(100,5,1,10)
f = {a,b}

现在,我想尽可能深入,并将cellfun 应用于f 的最深层次。在每一层的 和 ,都有一个 2D/3D 矩阵。比方说,我只想给每个值加 5。最有效的方法是什么?

这是我正在寻找的结果。

[a_nRows, a_nCols, a_nPages] = size(a)
x = cellfun(@plus, f{1}, repmat({5}, a_nRows, a_nCols, a_nPages), 'UniformOutput', false)
y = cellfun(@plus, f(2), {5}, 'UniformOutput', false)

【问题讨论】:

    标签: matlab multidimensional-array nested-loops cell-array


    【解决方案1】:

    您可以为此使用递归。

    首先,定义一个做两件事之一的函数

    1. 如果输入是数字矩阵,请应用一些运算。
    2. 如果输入是一个单元格,则调用这个相同的函数并将单元格的内容作为输入。

    函数看起来像这样(在本地定义到另一个函数或在它自己的 m 文件中):

    function out = myfunc( in, op )
        if iscell( in )
            out = cellfun( @(x) myfunc(x, op), in, 'UniformOutput', false );
        elseif isnumeric( in )
            out = op( in );
        else
            error( 'Cell contents must be numeric or cell!' )
        end
    end
    

    然后你可以在你的手机上拨打myfunc。这是一个与您类似的示例:

    a = {[1 2; 3 4], {eye(2), 10}}; % Nested cell arrays with numeric contents
    op = @(M) M + 5;                % Some operation to apply to all numeric contents
    
    myfunc( a, op )
    % >> ans = 
    %     { [6 7; 8 9], {[6 5; 5 6], 15}}
    

    直接使用您的示例,myfunc(f, @(M)M+5) 的输出与您的{x, y{1}} 相同 - 即操作op 应用于每个单元格和嵌套单元格,结果结构与输入相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多