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!