1

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
horseshoe
  • 1,437
  • 14
  • 42

1 Answers1

1

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(:) );
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 1
    @ Shai: Thanks, that was what I was looking for. Thinking a bit more about it I figured that reshape should also do it... `sum(reshape(mydata,cat_size,[]))` – horseshoe Dec 03 '15 at 10:14
  • @horseshoe indeed, if `numel(mydata)` is an integer multiply of `cat_size` then using `reshape` might even be better than `accumarray`. – Shai Dec 03 '15 at 10:16
  • @ Shai: Ah you are right, and I might have exactly this as my data are indeed 361 long and not 360. So I will stick with your solution. Still leaves the second one to solve... – horseshoe Dec 03 '15 at 10:18
  • 1
    @horseshoe why not posting them as two separate questions? the second part is not very clear. Can you add an illustration/figure of what you got and what you actually want to get? – Shai Dec 03 '15 at 10:19