# Creating averages for parts of an array in a for loop

1 view (last 30 days)
Jack Upton on 26 Nov 2019
Commented: Stephen Cobeldick on 26 Nov 2019
Hi,
I have 200 instances of data within an array and I would like to create a (mean) average using the last 5 instances of data for every data point.
The code I am currently using to manually do this is as follows:
a1=mean(a(1)); A1=a(1)-a1;
a2=mean(a(1:2)); A2=a(2)-a2;
a3=mean(a(1:3)); A3=a(3)-a3;
a4=mean(a(1:4)); A4=a(4)-a4;
a5=mean(a(1:5)); A5=a(5)-a5;
a6=mean(a(2:6)); A6=a(6)-a6;
a7=mean(a(3:7)); A7=a(7)-a7;
a8=mean(a(4:8)); A8=a(8)-a8;
a9=mean(a(5:9)); A9=a(9)-a9;
a10=mean(a(6:10)); A10=a(10)-a10;
Is there anyway I could use a for loop to drastically reduce the amount of code needed?
Jack

#### 1 Comment

Stephen Cobeldick on 26 Nov 2019
"Is there anyway I could use a for loop to drastically reduce the amount of code needed?"
Using numbered variables is a sign that you are doing something wrong, and are not taking advantage of MATLAB's strengths (processing arrays, indexing, etc.).
Copy-and-pasting code is also a sign that you are doing something wrong.

Stephen Cobeldick on 26 Nov 2019
Edited: Stephen Cobeldick on 26 Nov 2019
Your definitions of the boundary cases make this a bit tricky, but here is one solution:
>> A = randi(9,1,10)
A =
3.00 2.00 2.00 2.00 3.00 6.00 8.00 1.00 8.00 2.00
>> F = @(n)mean(A(max(1,n-N+1):n));
>> M = arrayfun(F,1:numel(A))
M =
3.00 2.50 2.33 2.25 2.40 3.00 4.20 4.00 5.20 5.00
You could also use conv , although you would need to handle the boundary cases yourself.

Jack Upton on 26 Nov 2019
Sorry this is the full code, with boundary cond.
t=X(:,1); %Time Values
g=X(:,2); %Acceleration Values
a=g*9.81; %convert to m/s^2
a1=mean(a(1)); A1=a(1)-a1;
a2=mean(a(1:2)); A2=a(2)-a2;
a3=mean(a(1:3)); A3=a(3)-a3;
a4=mean(a(1:4)); A4=a(4)-a4;
a5=mean(a(1:5)); A5=a(5)-a5;
a6=mean(a(2:6)); A6=a(6)-a6;
a7=mean(a(3:7)); A7=a(7)-a7;
a8=mean(a(4:8)); A8=a(8)-a8;
a9=mean(a(5:9)); A9=a(9)-a9;
a10=mean(a(6:10)); A10=a(10)-a10;
I have managed to calculate the moving average using the conv command, is there now a way to calculate the rate of change of conv?
Stephen Cobeldick on 26 Nov 2019
"is there now a way to calculate the rate of change of conv"
It is not clear what "rate of change of conv" means. Perhaps you want diff.