Chr*_* Su 4 matlab row sum matrix
有没有什么办法可以总结矩阵中每组三行的列值?
我可以手动方式将三行加起来.
例如
% 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))
...
Run Code Online (Sandbox Code Playgroud)
但是如果数据集很大,那就不行了.
有没有办法在没有循环的情况下自动执行此操作?
以下是其他四种方式:
强制性的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
Run Code Online (Sandbox Code Playgroud)使用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));
Run Code Online (Sandbox Code Playgroud)使用第三维(基于此):
% 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]);
Run Code Online (Sandbox Code Playgroud)使用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));
Run Code Online (Sandbox Code Playgroud)当然,到目前为止所有的解决方案都假设行数可以均分3
.