# How do I create a vector of the average of consecutive elements of another vector (without using a loop)?

39 views (last 30 days)
Rinu on 10 Oct 2013
Commented: Sk Rafidul on 11 May 2019
Say, I have a vector A=[2 4 6 8 10]. Is there any way I can create a vector of the average of consecutive elements of A, i.e. B=[3 5 7 9] without using a loop? Is there any matlab function to do that? Thanks in advance.

Azzi Abdelmalek on 10 Oct 2013
Edited: Azzi Abdelmalek on 10 Oct 2013
A=[2 4 6 8 10]
B=mean([A(1:end-1);A(2:end)])
Rinu on 10 Oct 2013
Thanks, that's a very simple way to do that.
Sk Rafidul on 11 May 2019

Jan on 10 Oct 2013
Edited: Jan on 10 Oct 2013
This is simpler and occupies less temporary memory than Azzi's approach:
A = [2 4 6 8 10];
B = 0.5 * (A(1:end-1) + A(2:end))
Rinu on 11 Oct 2013
Thanks a lot.

Matthew Crema on 10 Oct 2013
One way:
A=[2 4 6 8 10];
foo = conv([1 1], A)/2;
B = foo(2:end-1)
B =
3 5 7 9
-Matt
Jan on 11 Oct 2013
The speed argument might change, when the data exceed a certain size.
Andrei Bobrov on 11 Oct 2013
Edited: Andrei Bobrov on 11 Oct 2013
conv2(A,[.5 .5],'valid')