我有一个大小为 <20x1x19> 的单元格数组 C,19 个元素中的每个元素都包含一组 20 个大小为 (80x90) 的矩阵,我如何计算每个 20 个矩阵的平均值并将结果存储在矩阵 M 中所以最后我将有一个大小为 80x90x19 的矩阵,其中包含单元阵列矩阵的平均值。
例如:
M(:,:,1) 将具有 C(:,:,1) 中元素的平均值;
M(:,:,2) 将具有 C(:,:,2) 中元素的平均值
等等。
一点点数组操作可以让你放弃循环。您可以更改元胞数组的维度,从而生成cell2mat
一个 80×90×19×20 数组,之后您需要做的就是沿维度 #4 取平均值:
%# C is a 20x1x19 cell array containing 80x90 numeric arrays
%# turn C into 1x1x19x20, swapping the first and fourth dimension
C = permute(C,[4 2 3 1]);
%# turn C into a numeric array of size 80-by-90-by-19-by-20
M = cell2mat(C);
%# average the 20 "slices" to get a 80-by-90-by-19 array
M = mean(M,4);
假设我对您的理解正确,您可以通过以下方式做您想做的事情(评论逐步解释了我所做的事情):
% allocate space for the output
R = zeros(80, 90, 19);
% iterate over all 19 sets
for i=1:19
% extract ith set of 20 matrices to a separate cell
icell = {C{:,1,i}};
% concatenate all 20 matrices and reshape the result
% so that one matrix is kept in one column of A
% as a vector of size 80*90
A = reshape([icell{:}], 80*90, 20);
% sum all 20 matrices and calculate the mean
% the result is a vector of size 80*90
A = sum(A, 2)/20;
% reshape A into a matrix of size 80*90
% and save to the result matrix
R(:,:,i) = reshape(A, 80, 90);
end
您可以直接跳过提取icell
并连接第 i 组 20 个矩阵
A = reshape([C{:,1,i}], 80*90, 20);
我在这里只是为了清楚起见。
上面的步骤可以更简短(但肯定更神秘!)通过以下arrayfun
调用表示:
F = @(i)(reshape(sum(reshape([C{:,1,i}], 80*90, 20), 2)/20, 80, 90));
R = arrayfun(F, 1:19, 'uniform', false);
R = reshape([R2{:}], 80, 90, 19);
匿名函数F
本质上是循环的一次迭代。它被 调用 19 次arrayfun
,每组矩阵调用一次。我建议你坚持循环。