Averaging values within bins

168 views (last 30 days)
MiauMiau
MiauMiau on 28 Oct 2018
Commented: Bruno Luong on 13 Jun 2022
Hi,
I have the two arrays x and y (attached), which I plot with plot(x,y). This is creating "bins" of width 5:
What is the fastest way to average the values within each such bin, such that we end up with one value/bin, especially if we don't want to pre-define bin width?
Thanks
  3 Comments
Stephen23
Stephen23 on 28 Oct 2018
"Would the histogram function help nevertheless?"
Yes, because they can also return the indices.

Sign in to comment.

Answers (2)

Bruno Luong
Bruno Luong on 28 Oct 2018
load('y.mat')
load('x.mat')
plot(x,y)
edges = (0:5:50);
[~,~,loc]=histcounts(x,edges);
meany = accumarray(loc(:),y(:))./accumarray(loc(:),1);
xmid = 0.5*(edges(1:end-1)+edges(2:end));
figure
plot(x,y)
hold on;
plot(xmid,meany,'r')
  2 Comments
Bruno Luong
Bruno Luong on 13 Jun 2022
Simply remove the bad data:
keep = isfinite(x) & isfinit(y);
x = x(keep);
y = y(keep);
... do the rest
Make sure the extrem edges cover entirely your data.

Sign in to comment.


Steven Lord
Steven Lord on 28 Oct 2018
Do you want to use histogram or histcounts to bin the data, or are you looking for something more of a moving average, where the value of the averaged signal at a particular time is the mean of the data for that time and some data points before and after that time? If the latter, see movmean.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by