Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Averaging every n elements of a vector in matlab

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.

like image 785
gtdevel Avatar asked Dec 15 '22 18:12

gtdevel


2 Answers

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.

like image 118
glglgl Avatar answered Jan 02 '23 20:01

glglgl


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

like image 42
nicktruesdale Avatar answered Jan 02 '23 20:01

nicktruesdale