matlab - 对矩阵的每 n 行求和

标签 matlab matrix sum row

有什么方法可以对矩阵中每组三行的列值求和吗?
我可以手动总结三行。

例如

% matrix is the one I wanna store the new data.
% data is the original dataset.
matrix(1,1:end) = sum(data(1:3, 1:end))
matrix(2,1:end) = sum(data(4:6, 1:end))
...

但是如果数据集很大,这就不行了。
有什么方法可以自动执行此操作而无需循环?

最佳答案

还有其他四种方式:

  1. 必需的 for 循环:

    % for-loop over each three rows
    matrix = zeros(size(data,1)/3, size(data,2));
    counter = 1;
    for i=1:3:size(data,1)
        matrix(counter,:) = sum(data(i:i+3-1,:));
        counter = counter + 1;
    end
    
  2. 使用 mat2cell 进行平铺:

    % divide each three rows into a cell
    matrix = mat2cell(data, ones(1,size(data,1)/3)*3);
    
    % compute the sum of rows in each cell
    matrix = cell2mat(cellfun(@sum, matrix, 'UniformOutput',false));
    
  3. 使用三维(基于 this ):

    % put each three row into a separate 3rd dimension slice
    matrix = permute(reshape(data', [], 3, size(data,1)/3), [2 1 3]);
    
    % sum rows, and put back together
    matrix = permute(sum(matrix), [3 2 1]);
    
  4. 使用accumarray:

    % build array of group indices [1,1,1,2,2,2,3,3,3,...]
    idx = floor(((1:size(data,1))' - 1)/3) + 1;
    
    % use it to accumulate rows (appliead to each column separately)
    matrix = cell2mat(arrayfun(@(i)accumarray(idx,data(:,i)), 1:size(data,2), ...
        'UniformOutput',false));
    

当然,目前所有的解决方案都假设行数可以被 3 整除。

关于matlab - 对矩阵的每 n 行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18796406/

相关文章:

c++ - MatLab C++ 共享 Dll 库初始化崩溃

c++ - 如何在 C++ 中使用 2 个循环制作一个完整的矩阵

matlab - 在 Matlab 中取具有 NaN 的矩阵的平均值

math - Scala 矩阵求逆

mysql - 计数考虑 3 列的总和

c++ - 如何在类,c++中使用带参数的函数?

java - EJBQL 命名查询 - 如何对 BigDecimal 求和

Matlab logncdf 函数未产生预期结果

arrays - 将两列位合并为一列

matlab - 为什么复杂的 Matlab gpuArray 占用的内存是它应该占用的内存的两倍?