【问题标题】:compute the means of a 3-dimensional cell array in matlab在 matlab 中计算 3 维元胞数组的均值
【发布时间】:2012-09-30 17:52:28
【问题描述】:

我有一个大小为 的元胞数组 C,19 个元素中的每一个都包含 一组 20 个大小 (80x90) 的矩阵, 如何计算每个 20 矩阵的平均值并将结果存储在矩阵 M 中,这样最后我将拥有一个大小为 80x90x19 的矩阵,其中包含单元阵列矩阵的均值。

例如:

M(:,:,1) 将具有 C(:,:,1) 中元素的平均值;

M(:,:,2) 将具有 C(:,:,2) 中元素的平均值

等等。

【问题讨论】:

    标签: arrays matlab matrix cell mean


    【解决方案1】:

    一点点数组操作可以让您放弃循环。您可以更改元胞数组的维度,以便 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);
    

    【讨论】:

    • +1 非常干净的代码。尽管cell2mat 扼杀了性能。它比我电脑上的循环慢 4 倍..
    【解决方案2】:

    假设我对你的理解正确,你可以按照以下方式做你想做的事(cmets 一步一步解释我做了什么):

    % 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 本质上是循环的一次迭代。 arrayfun 调用了 19 次,每组矩阵调用一次。我建议你坚持循环。

    【讨论】:

    • 我建议使用mean 而不是sum(x)/n
    猜你喜欢
    • 2015-10-31
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2016-08-01
    相关资源
    最近更新 更多