有什么方法可以对矩阵中每组三行的列值求和吗?
我可以手动总结三行。
例如
% 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))
...
但是如果数据集很大,这就不行了。
有什么方法可以自动执行此操作而无需循环?
最佳答案
还有其他四种方式:
必需的
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
使用
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));
使用三维(基于 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]);
使用
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/