How to average 5 rows of a vector recursively?

3 vues (au cours des 30 derniers jours)
Samuel White
Samuel White le 30 Jan 2019
Commenté : Ollie A le 30 Jan 2019
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

Réponse acceptée

Ollie A
Ollie A le 30 Jan 2019
Modifié(e) : Ollie A le 30 Jan 2019
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 commentaires
Guillaume
Guillaume le 30 Jan 2019
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 le 30 Jan 2019
I agree with Guillaume that his answer is more efficient.

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 30 Jan 2019
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')

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by