0

I have a vector A of size 7812x1 and would like to calculate the sum of fixed windows of length 21 (so 372 blocks). This should be reiterated, so that the output should return a vector of size 372x1.

I have t=7812, p=372, w=21;

for t=1:p
   out = sum(A((t*w-w+1):(t*w)));
end

This code, however, does not work. My idea is that the part ((t*w-w+1):(t*w)) allows for something like a rolling window. The window is of length 21, so there is not really a need to express is with variables, yet I think it keeps some flexibility.

I've seen potentially related questions (such a partial sum of a vector), yet I'm not sure whether this would result the output desired.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Joe
  • 457
  • 5
  • 18

2 Answers2

3

Reshape into a matrix so that each block of A is a column, and compute the sum of each colum:

result = sum(reshape(A, w, []), 1);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • I guess in my case it should be the sum instead of the mean, in order to obtain the same results as @Leander Moesinger. Otherwise, I'm taking the mean of each block, right?. However, the solution is intuitive and works perfectly well. Many thanks! – Joe Nov 06 '17 at 11:50
  • @Joe Yes, sum instead of mean, sorry. Corrected – Luis Mendo Nov 06 '17 at 12:15
1

Following your idea of using a rolling/moving window (requires Matlab 2016a or later):

t = 7812; w = 21; % your parameters
A = rand(t,1); % generate some test data

B = movsum(A,w); % the sum of a moving window with width w
out = B(ceil(w/2):w:end); % get every w'th element
Leander Moesinger
  • 2,449
  • 15
  • 28