Find average y value of a range of numbers from a non linear data set
3 views (last 30 days)
Show older comments
I have a data set of around 200000 lines. The data has 2 columns say x and y. I am giving a simplified example of the same below. X = [1, 5, 7, 12, 18, 25] Y= [20, 25, 32, 28, 27, 31]
This means for x values 1 to 4 y value is 20. For x =5 and 6 y = 25. For x=7 to 11 y =25 like that. Now I want to calcate average of subsets of x with 5 numbers. For example average of y of x values 1:5, then 6:10, 11:15 etc. For example, I expect average of 6:10 subset as [25*1(y value of x=6) + 32*4(y value of 7,8,9,10)] ÷ 5. What is the simplest way for doing this in matlab. I am a beginner in matlab programming.
0 Comments
Accepted Answer
the cyclist
on 20 Aug 2019
Edited: the cyclist
on 20 Aug 2019
Your example of averaging the values from 6:10 would be
mean(interp1(X,Y,6:10,"previous"))
Change where I put 6:10 to be the actual range you want.
The documentation for interp1 will explain the "previous" method of interpolation, which is crucial to how this works.
You can do multiple sets of 5 at once, like this:
mean(interp1(X,Y,[1:5; 6:10]',"previous"))
The first number is the average of the first 5 elements, and the second one is the next 5.
It's easy to generalize this even further.
More Answers (1)
MARTIN FABRET
on 20 Aug 2019
function m = Meanfcn(X,Y,start,last)
firstIndex = 1;
while start < X(firstIndex)
firstIndex = firstIndex + 1;
end
l = last-start;
s = 0;
for i=0:1:l
if start+i>=X(firstIndex) && start+i<X(firstIndex+1)
s=s+Y(firstIndex);
else
firstIndex = firstIndex+1;
s=s+Y(firstIndex);
end
end
m = s/(l+1);
end
0 Comments
See Also
Categories
Find more on Interpolation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!