How can I create another matrix with the sum of every 30 rows in a 14,400 by 11 matrix?
6 次查看(过去 30 天)
显示 更早的评论
I have a matrix with 11 columns of daily data for 40 years (14,400 days) and need the sum of every 30 days to be calculated. After looking around a lot I decided I'd ask on here. Thanks in advance for the help!
0 个评论
采纳的回答
更多回答(5 个)
Image Analyst
2014-6-13
Did you try the brute force approach? It's pretty simple and intuitive and fast:
m = randi(9, [14400, 11]);
otuputRow = 1;
for row = 1 : 30 : size(m, 1)
theSums(otuputRow, :) = sum(m(row:row+29,:));
otuputRow = otuputRow + 1;
end
theSums
0 个评论
Matt J
2014-6-13
If the 30-day blocks to be summed are tiled, you can also do
result = downsampn(yourMatrix,[30,1])*30;
where downsampn is given by,
function M=downsampn(M,bindims)
%DOWNSAMPN - simple tool for downsampling n-dimensional nonsparse arrays
%
% M=downsampn(M,bindims)
%
%in:
%
% M: an array
% bindims: a vector of integer binning dimensions
%
%out:
%
% M: the downsized array
nn=length(bindims);
[sz{1:nn}]=size(M); %M is the original array
sz=[sz{:}];
newdims=sz./bindims;
args=num2cell([bindims;newdims]);
M=reshape(M,args{:});
for ii=1:nn
M=mean(M,2*ii-1);
end
M=reshape(M,newdims);
1 个评论
Cedric
2014-6-13
I don't think that we can beat this one. I expected Andrei's solution to be faster, but it seems that dealing with pages makes it slower than iterating over "bindims"..
Cedric
2014-6-13
编辑:Cedric
2014-6-13
Here are a couple additional ways, if you need a sum for each block of 30 days (not a "moving" sum), assuming that your original matrix is named M:
Base on accumarray
M_aggregated = zeros( size(M,1)/30, size(M,2) ) ;
blockId = zeros( size(M,1), 1 ) ;
blockId(1:30:end) = 1 ;
blockId = cumsum( blockId ) ;
for cId = 1 : size(M,2)
M_aggregated(:,cId) = accumarray( blockId, M(:,cId) ) ;
end
Based on matrix product
% - Build aggregation matrix.
aggr = repmat( {ones(1,30)}, size(M,1)/30, 1 ) ;
aggr = blkdiag( aggr{:} ) ;
% - Aggregate data.
M_aggregated = aggr * M ;
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!