Automate an averaging process and store info into an array
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Keshav
2022-7-4
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 个评论
Keshav
2022-7-5
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!