How can I create another matrix with the sum of every 30 rows in a 14,400 by 11 matrix?
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
txvmi07
le 13 Juin 2014
Commenté : Habeeb Alasadi
le 2 Juil 2015
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 commentaires
Réponse acceptée
Plus de réponses (5)
Image Analyst
le 13 Juin 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
0 commentaires
Matt J
le 13 Juin 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 commentaire
Cedric
le 13 Juin 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"..
Cedric
le 13 Juin 2014
Modifié(e) : Cedric
le 13 Juin 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 ;
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!