MATLAB: Finding average of every nth row

averagecolumn vectorfor looploopsmeanmoving averagenth rowrolling average

I have a column vector that is 9985×1. I want to create a new vector that lists the average of every 6 rows in the column. How can I do this? Is there a way to do it with a loop?
Thank you!

Best Answer

This is the mean over 6 subsequent rows:
x = rand(9985, 1);
S = numel(x);
xx = reshape(x(1:S - mod(S, 6)), 6, []);
y = sum(xx, 1).' / 6;
The trailing rows are ignored.
[EDITED] General method for matrices:
x = rand(9985, 14);
p = 6;
n = size(x, 1); % Length of first dimension
nc = n - mod(n, p); % Multiple of p
np = nc / p; % Length of result
xx = reshape(x(1:nC, :), p, np, []); % [p x np x size(x,2)]
y = sum(xx, 1) / p; % Mean over 1st dim
y = reshape(y, np, []); % Remove leading dim of length 1