Given a matrix of random data x
:
x = randn(27,16800);
you can compute the average over all groups of n=10
values along the rows in two similar ways as described by Luis Mendo and Brice in comments:
y = permute(mean(reshape(x.', n, [], size(x,1)), 1), [3 2 1]); % Luis
y = squeeze(mean(reshape(x,size(x,1),n,[]),2)); % Brice
However, as noted by Wolfie, these work only if the length of the rows is exactly divisible by n
.
A more general approach can be obtained by convolving:
y = conv2(x,ones(1,n)/n,'valid');
y = y(:,1:n:end);
Each matrix element in the output of the convolution is the average over n
values. This result is n-1
elements shorter than the input. That is, we have computed n
times as many averages as needed. The second line takes the first of every n
averages, yielding an output of the expected size.
The convolution yields a result that is different from the other methods by numerical imprecision (max difference is 4.4409e-16 on my machine). This is because conv2
is implemented using SIMD instructions of your CPU, whereas mean
likely is not. The convolution approach might be somewhat slower than the other approach, but it is generic and easy to adapt.
n = 10; result = permute(mean(reshape(x.', n, [], size(x,1)), 1), [3 2 1]);
wherex
is the data matrix – Luis Mendo Nov 19 '18 at 14:30