MATLAB Answers

Averaging values within bins

193 views (last 30 days)
MiauMiau
MiauMiau on 28 Oct 2018
Answered: Steven Lord on 28 Oct 2018
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
Stephen
Stephen 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')

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!