Help with for cycle in a vector

1 visualización (últimos 30 días)
aurc89
aurc89 el 29 de Abr. de 2014
Editada: Andrei Bobrov el 29 de Abr. de 2014
I have a vector , and I want to obtain another vector whose elements are obtained by averaging over the elements of the first one. For example I have
x = [3,6,4,5,1,7,9,8,5]
and I want to obtain a vector by averaging every 3 elements of x, like this
y = [(3+6+4)/3,(5+1+7)/3,(9+8+5)/3].
Also I want to take into account the modulus of division, so if I have
x=[3,6,4,5,1,7,9,8]
then y should be
y = [(3+6+4)/3,(5+1+7)/3,(9+8)/2],
and if
x=[3,6,4,5,1,7,9]
then y should be
y = [(3+6+4)/3,(5+1+7)/3,9]
I know I have to use more than a 'for' cycle but don't know how, could you help me? thanks

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 29 de Abr. de 2014
x = [3,6,4,5,1,7,9,8,5]
p=mod(-numel(x),3)
x(end+1:end+p)=mean(x(end:-1:end-(3-p)+1))
out=mean(reshape(x,3,[]))

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 29 de Abr. de 2014
Editada: Andrei Bobrov el 29 de Abr. de 2014
out = blockproc(x,[1,3],@(x)mean(x.data));
or
out = nanmean(reshape([x,nan(1,mod(-numel(x),3))],[],3));

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by