Oliver Amundsen
Oliver Amundsen

Reputation: 1511

Average on contiguos segments of a vector

I'm sure this is a trivial question for a signals person. I need to find the function in Matlab that outputs averaging of contiguous segments of windowsize= l of a vector, e.g.

origSignal: [1 2 3 4 5 6 7 8 9];
windowSize = 3;
output = [2 5 8]; % i.e. [(1+2+3)/3 (4+5+6)/3 (7+8+9)/3]

EDIT: Neither one of the options presented in How can I (efficiently) compute a moving average of a vector? seems to work because I need that the window of size 3 slides, and doesnt include any of the previous elements... Maybe I'm missing it. Take a look at my example...

Thanks!

Upvotes: 3

Views: 70

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

If the size of the original data is always a multiple of widowsize:

mean(reshape(origSignal,windowSize,[]));

Else, in one line:

mean(reshape(origSignal(1:end-mod(length(origSignal),windowSize)),windowSize,[]))

This is the same as before, but the signal is only taken to the end minus the extra values less than windowsize.

Upvotes: 3

Related Questions