Averaging every n elements of a vector in matlab

2019-01-26 18:02发布

问题:

I would like to average every 3 values of an vector in Matlab, and then assign the average to the elements that produced it.

Examples:

x=[1:12];
y=%The averaging operation;

After the operation,

y=
[2 2 2 5 5 5 8 8 8 11 11 11]

Therefore the produced vector is the same size, and the jumping average every 3 values replaces the values that were used to produce the average (i.e. 1 2 3 are replaced by the average of the three values, 2 2 2). Is there a way of doing this without a loop?

I hope that makes sense.

Thanks.

回答1:

I would go this way:

Reshape the vector so that it is a 3×x matrix:

x=[1:12];
xx=reshape(x,3,[]);
% xx is now [1 4 7 10; 2 5 8 11; 3 6 9 12]

after that

yy = sum(xx,1)./size(xx,1)

and now

y = reshape(repmat(yy, size(xx,1),1),1,[])

produces exactly your wanted result.

Your parameter 3, denoting the number of values, is only used at one place and can easily be modified if needed.



回答2:

You may find the mean of each trio using:

x = 1:12;
m = mean(reshape(x, 3, []));

To duplicate the mean and reshape to match the original vector size, use:

y = m(ones(3,1), :) % duplicates row vector 3 times
y = y(:)'; % vector representation of array using linear indices