Averaging every n elements of a vector in matlab

戏子无情 提交于 2019-11-29 11:23:04

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!