Creating averages for parts of an array in a for loop
1 次查看(过去 30 天)
显示 更早的评论
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
1 个评论
Stephen23
2019-11-26
编辑:Stephen23
2019-11-26
"Is there anyway I could use a for loop to drastically reduce the amount of code needed?"
Using numbered variables is entirely the wrong way to go about this task.
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.
回答(1 个)
Stephen23
2019-11-26
编辑:Stephen23
2019-11-26
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.
2 个评论
Stephen23
2019-11-26
"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.
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!