Borrar filtros
Borrar filtros

How to average 5 rows of a vector recursively?

3 visualizaciones (últimos 30 días)
Samuel White
Samuel White el 30 de En. de 2019
Comentada: Ollie A el 30 de En. de 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

Respuesta aceptada

Ollie A
Ollie A el 30 de En. de 2019
Editada: Ollie A el 30 de En. de 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 comentarios
Guillaume
Guillaume el 30 de En. de 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 el 30 de En. de 2019
I agree with Guillaume that his answer is more efficient.

Iniciar sesión para comentar.

Más respuestas (1)

Guillaume
Guillaume el 30 de En. de 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')

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by