How to average 5 rows of a vector recursively?

1 次查看(过去 30 天)
I have a very long 1D vector ~ 9445 long. I wish to take the average of sets of 5 down the vector and send them to a new vector for example:
1
2
3
4
5
6
7
8
9
10
would become
3
8
How can I do this easily?
Many thanks

采纳的回答

Ollie A
Ollie A 2019-1-30
编辑:Ollie A 2019-1-30
V = 1:9445; % Your vector
setsize = 5;
for x = 1:length(V)/setsize
Vnew(x) = mean(V((x-1)*setsize+1:x*setsize))
end
I hope this is simple enough.
  4 个评论
Guillaume
Guillaume 2019-1-30
It's unfortunate you've accepted that answer which is overly complicated and slow and not the matlab way. The lack of preallocation of the output is also going to be a problem if you're not careful.
However, as long as Vnew did not exist before running that code, it will produce a vector.
For the proper way to do what you want in matlab, see my answer.
Ollie A
Ollie A 2019-1-30
I agree with Guillaume that his answer is more efficient.

请先登录,再进行评论。

更多回答(1 个)

Guillaume
Guillaume 2019-1-30
As long as the length of your vector is a multiple of 5:
mean(reshape(yourvector, 5, []), 1)
If the length is not a multiple of 5, pad it first with NaNs to a multiple of 5 and do the same as above, with the 'omitnan' flag for mean:
paddedvector = [yourvector; nan(mod(-numel(yourvector), 5), 1)]; %pad to a length multiple of 5
mean(reshape(paddedvector, 5, []), 1, 'omitnan')

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by