Finding average of every nth row?
79 次查看(过去 30 天)
显示 更早的评论
I have a column vector that is 9985x1. 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!
采纳的回答
Jan
2017-11-13
编辑:Jan
2019-4-4
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
See also FEX: BlockMean
6 个评论
更多回答(3 个)
Andrei Bobrov
2017-11-13
编辑:Andrei Bobrov
2017-11-13
Let A - your array (9985 x 1).
out = splitapply(@mean,A,ceil((1:numel(A))'/6));
or
out = accumarray(ceil((1:numel(A))'/6),A(:),[],@mean);
Joe S
2018-12-26
These answers work when dim=1 but appears to fail for ndims =2 (multiple columns). To average nRows together (variable "gps") for ndims=2, see below. You have the option of including the average of the "modulus rows" with: includeMods=1.
%create simple matrix, easier to check vs. random numbers
nRows = 11;
nCols = 3;
includeMods=1;
x = reshape(1:(nRows*nCols),[nRows,nCols]);
%provide row number to average over
grps = 3;
%determine remainder rows from Modulo operation
exRows = mod(nRows,grps);
% work with the top portion that group "cleanly"
topM = x(1:end-exRows,:);
%gather dims for reshaping
nRowsTop = size(topM,1);
numTop = numel(topM);
%Reshape so nrows = grps (row number to average over)
flatTop = reshape(topM,[grps numTop./grps]);
%take averages
meanTop = mean(flatTop,1);
% reshape back to original number of columns
final = reshape(meanTop,[nRowsTop./grps nCols]);
%optional, average the modulus rows, add back into final answer
if includeMods
if ~(exRows==0)
exMat= x(end-exRows+1:end,:);
meanEx = mean(exMat,1);
final = vertcat(final,meanEx);
end
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!