Automate an averaging process and store info into an array
1 view (last 30 days)
Show older comments
I have a code that takes the average of every 2 points of an array by changing k:
mdata = [1:10];
n1 = 1;
k = 1;
for n = 1:length(mdata)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
n1 = (n1 + k) + 1;
std_ma = std(ma);
end
I want to be able to automate a process that increases the averaging size each time (ex: 2 points averaged each time of an array, then 3 points averaged each time of an array, 4 points averaged, … n points averaged) and then stores all of that averaged data into a single array.
For example, if we have 2000 data points and we take the average of every 2 points, we’d end up with 1x1000. Then if we do 3 points averaged, we get 1x666~, 4 averaged we get 1x500, etc. I want to automate this and have all of that information stored into a single array.
Not sure how to go about it, any help?
0 Comments
Answers (1)
Keshav
on 4 Jul 2022
Hi, Based on my understanding you want to first calculate the average of 2 elements, 3 elements,... n elements. so if the array is [1 2 3 .... 10] then you want to make an array ans such that
ans = [avg(1,2) avg(3,4) .... avg(9,10) avg(1,2,3) avg(4,5,6) avg(7,8,9) avg(1,2,3,4) ................... avg(1,2,3,4,....,10)]
as you have already written the code to find the average of two elements, I made it generalize for every possible k.
clc
clear
mdata = [1:10];
n1 = 1;
n = 1;
for k=1:length(mdata)-1
n1 = 1;
while n1+k <= length(mdata)
ma(n) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
n1 = (n1 + k) + 1;
std_ma = std(ma);
n = n + 1;
end
end
ma
2 Comments
Keshav
on 5 Jul 2022
you can use the below code to remove the extra zero. Just you have to reinitialize the value of n.
clc
clear
mdata = [1:10];
for k=1:length(mdata)-1
n1 = 1;
n = 1;
while n1+k <= length(mdata)
ma(n,k) = (1/(k + 1)) * sum(mdata(n1:n1 + k));
n1 = (n1 + k) + 1;
std_ma = std(ma);
n = n + 1;
end
end
ma
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!