4

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.

gtdevel
  • 1,513
  • 6
  • 21
  • 38

2 Answers2

9

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • Thanks thats great! Just a follow up. If you reshape the matrix, but there the size of the vector isn't divisible by 3, how will the matrix be reshaped? – gtdevel Oct 22 '12 at 14:54
3

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

nicktruesdale
  • 815
  • 5
  • 12
  • `mean` is better than doing it manually, and the indexing with `ones()` and `y(:)` are nice approaches, too. But I would transpose with `.'`, not with `'`. – glglgl Oct 25 '12 at 08:42
  • I know this is an old answer. Still, consider replacing `'` with `.'` as suggested. Reason: `'` without `.` is used to get the *complex conjugate* transpose knows as [`ctranspose`](http://ch.mathworks.com/help/matlab/ref/ctranspose.html). When using complex values, this will be problematic and hard to find. Refer to the documentation: *The nonconjugate transpose operator, `A.`', performs a transpose without conjugation. That is, it does not change the sign of the imaginary parts of the elements.* – Matt Apr 13 '16 at 14:43