How can I create another matrix with the sum of every 30 rows in a 14,400 by 11 matrix?

6 views (last 30 days)
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!

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 13 Jun 2014
out = squeeze(sum(reshape(yourdata',11,30,[]),2))';

More Answers (5)

Image Analyst
Image Analyst on 13 Jun 2014
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

Matt J
Matt J on 13 Jun 2014
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 Comment
Cedric
Cedric on 13 Jun 2014
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"..

Sign in to comment.


Matt J
Matt J on 13 Jun 2014
result = conv2(yourMatrix,ones(30,1),'valid');

Cedric
Cedric on 13 Jun 2014
Edited: Cedric on 13 Jun 2014
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 ;

txvmi07
txvmi07 on 16 Jun 2014
Thank you everyone for your generous help! All of your suggestions worked great and seeing all the different methodologies was extremely helpful. I've generated a hyperbolic decline curve for an oil and gas well in order to estimate the ultimate volumes that it will produce over 40 years (~14,400 days). While having this data on a daily basis is great it's more function to further analysis on a monthly basis.
I will say that Andrei's response was likely the simplest, but that all examples worked perfectly.
Thanks again!

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!