How to calculate the means of n adjacent units of a vector?

Hi, i have a question about vectors.
For example i have a vector A=[1 2 3 4 5 6 7 8 9 10]T I want to get the mean values of every two adjacent units in this vector. I mean i should get B=[1,5 2,5 3,5 4,5 5,5 6,5 7,5 8,5 9,5]T
1,5=(1+2)/2 , 2,5=(2+3)/2 etc.
or every 3 units i should get: C=[2 3 4 5 6 7 8 9]T
2=(1+2+3)/3 , 3=(2+3+4)/3 etc.
or every 4 units i should get: D=[2,5 3,5 4,5 5,5 6,5 7,5 8,5]T etc.
Is there any way to do that for large vectors by using mean() function easily (not using any loop)?
Thanks in advance

 채택된 답변

Roger Stafford
Roger Stafford 2015년 2월 9일
If you want the mean of each n successive values in A, to place it in X, do this:
X = mean(hankel(A(1:n),A(n,end)),1);

댓글 수: 5

Thanks for the answer, but this still gives a 1x1 vector.
There's a typo in Roger's answer (should be A(n:end)) but otherwise, it works exactly as you want:
cummean = @(V, n) mean(hankel(V(1:n), V(n:end)), 1);
A = [1 2 3 4 5 6 7 8 9 10]
D = cummean(A, 4)
returns:
D =
2.5 3.5 4.5 5.5 6.5 7.5 8.5
Roger Stafford
Roger Stafford 2015년 2월 9일
편집: Roger Stafford 2015년 2월 9일
Not if length(A) is greater than n. Set n = 2 and try it on your example for A = 1:10. You should get the B you described. Set n = 4 and get your D.
Oops, you're right, Guillaume. It should be
X = mean(hankel(A(1:n),A(n:end)),1);
Oh, thanks. It works fine for now.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

질문:

2015년 2월 9일

댓글:

2015년 2월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by