1 view (last 30 days)

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?

Thanks in advance,

Jack

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.

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.

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/493294-creating-averages-for-parts-of-an-array-in-a-for-loop#comment_771608

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/493294-creating-averages-for-parts-of-an-array-in-a-for-loop#comment_771608

Sign in to comment.