MATLAB:将cellfun与多级单元阵列结合使用
我有一个多级单元阵列。每个级别的大小可能不同。我想知道如何将MATLAB:将cellfun与多级单元阵列结合使用,matlab,multidimensional-array,nested-loops,cell-array,Matlab,Multidimensional Array,Nested Loops,Cell Array,我有一个多级单元阵列。每个级别的大小可能不同。我想知道如何将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
应用到最低级别。设想以下多级别单元阵列:
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)
您可以为此使用递归 首先,定义一个函数,它完成两件事中的一件
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
应用于每个单元格和嵌套单元格,其结果结构与输入相同
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}}