MATLAB Answers

Mean neighbour values of a vector

3 views (last 30 days)
Hi,
I got an original data(a vector, size is 1*N):
the format is like this: ๐‘ 1:๐‘ฅ1,๐‘ฅ2,๐‘ฅ3โ€ฆ๐‘ฅ๐‘
And I need 20 series,
The scale 2 series was obtained by averaging two successive values from the original series. Scale 3 was obtained by averaging every three original values and so on as shown in equation.
๐‘ 2:(๐‘ฅ1+๐‘ฅ2)/2,(๐‘ฅ3+๐‘ฅ4)/2,โ€ฆ,(๐‘ฅ๐‘โˆ’1+๐‘ฅ๐‘)/2
๐‘ 20:(๐‘ฅ1+โ‹ฏ+๐‘ฅ20)/20,โ€ฆ,(๐‘ฅ๐‘โˆ’20+โ‹ฏ+๐‘ฅ๐‘)/20
How can I achieve this in Matlab?

  1 Comment

Ameer Hamza
Ameer Hamza on 18 Nov 2020
Suppose you have an odd number of elements? How to calculate s2 in that case? For example, x have 5 elements.
s2 =: (x1+x2)/2, (x3+x4)/2, x5+????

Sign in to comment.

Accepted Answer

Srivardhan Gadila
Srivardhan Gadila on 24 Nov 2020
You can learn the essentials of MATLAB throught the MATLAB Onramp course. If you are already familiar then you can refer to the documentation of for, mean & Loops and Conditional Statements.
For the above cases listed ๐‘ 2:(๐‘ฅ1+๐‘ฅ2)/2,(๐‘ฅ3+๐‘ฅ4)/2,โ€ฆ,(๐‘ฅ๐‘โˆ’1+๐‘ฅ๐‘)/2 and ๐‘ 20:(๐‘ฅ1+โ‹ฏ+๐‘ฅ20)/20,โ€ฆ,(๐‘ฅ๐‘โˆ’20+โ‹ฏ+๐‘ฅ๐‘)/20, you can do something like below using arrayfun:
s1 = randn(40,1);
N = numel(s1);
m = 2;
s2 = arrayfun(@(i)mean(s1(m*(i-1)+1:m*i)),1:floor(N/m))
m = 20;
s20 = arrayfun(@(i)mean(s1(m*(i-1)+1:m*i)),1:floor(N/m))
Note that as Ameer Hamza rightly mentioned, you will have to figure out the code in the case where N is not exactly divisible by m.

  0 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!