Search code examples
matlabsumaggregatemulti-step

Building stepwise (aggregated) sum


I have a question related to aggregating data. Is there a fuction that does stepwise sums of an array. There must be some easy way but the words I googled didn't seem to be the right ones. So essentially what I want to do is this

mydata      = rand(360,1);
cat_size    = 10;
aggreg_sum  = zeros(ceil(length(mydata)/cat_size),1);
c = 1;
for i = 1:cat_size: length(mydata)
    aggreg_sum(c) = sum(mydata(i:(i+cat_size)-1));
    c=c+1;
end

Solution

  • Regarding your first question, you can use accumarray:

    subs = 0*mydata;
    subs(1:cat_size:end) = 1;
    subs = cumsum(subs);
    aggreg_sum = accumarray( subs(:), mydata(:) );