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.

0

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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 Yes, sum instead of mean, sorry. Corrected
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.