How can I estimate the average for each one of the intervals in an x axis?
17 views (last 30 days)
Adam Danz on 19 May 2019
Edited: Adam Danz on 20 May 2019
This is relatively straight forward with histcounts() and splitapply().
% Create fake data
x = randi(1000,1,1000); %doesn't have to be sorted
y = rand(size(x));
% Define the edges of your x data
% There's lots of ways to do this - this is just 1 example.
binWidth = 100; %how wide is each bin?
edges = min(x) : binWidth : max(x);
% determine which bin each x element is in
[~, ~, hbin] = histcounts(x,[edges,inf]);
% Get mean of y within each bin
% Here I ignore NaN values, too.
binMean = splitapply(@(x)mean(x,'omitna'),y,hbin);
To interpret the results, binMean(n) is the mean for all y values where x is greater or equal to edges(n) and less than edges(n+1).
To plot the data, the bins, and display the average values per bin above the axis:
text(edges+binWidth/2, ones(size(edges)), strsplit(num2str(binMean,.1)), ...
'VerticalAlignment', 'Bottom', 'HorizontalAlignment', 'Center')
% * binMean must be a row vector