Binning x and y

Hi all,
Assuming that I have the follwing data:
x=[0, 2, 2.4, 2.8, 3.4, 3.9, 4, 4,7, 5.3, 5.8, 6, 6.4......]; % unit of x is cm
y=[100, 50, 30, 25, 20, 16, 14, 13, 12, 11, 10.5, 10, ....]; % Intensity
My question is the following:
I can plot y vs. x but I Would like, for instance, to bin x with a constant bin width (constant distance). Let say bin width of 2 (constant distance 2 cm). Therefore I would like to obtain a new x called xn:
xn=[0, 2, 4, 6,..]
and yn should contain the sum of the data which are conatained in in each interval:
interval1=[0,2] contains 100+50=150
interval2=]2,4] contains 50 + 30 + 25 + 20 + 16 + 14 =155
interval3=]4,6] contains 56.5
yn=[150, 155, 56.5]
and then I would like to plot yn versu xn
your hepl is highly welcome....
cheers

Answers (1)

the cyclist
the cyclist on 5 Aug 2014

0 votes

You should be able to do this with the hist() or histc() command. You can specify your bin locations, and then get the index for which x values went into each bin. Then use that index to sum your y values.

5 Comments

Adam
Adam on 5 Aug 2014
Hi ,
Thanks for your quick reply: I did it in the following way:
[n,bin] = histc(x,linspace(min(x),max(x),200)); yn=full(mean(sparse(1:length(x),bin,y)))
but this gives the mean and not the sum. xn now is xn=1:200 ? ist correct?
cheers
The first part is basically right, but I'm not quite sure what you're doing in the definition of yn. I would do this:
% Same as your code, but I explicitly define the bin edges as a variable
binEdge = linspace(min(x),max(x),200);
[n,bin] = histc(x,binEdge);
% Sum up the values in each bin.
yn = accumarray(bin',y);
% Plot
figure
plot(binEdge,yn)
The accumarray function is a powerful one. It is effectively looping through all of the bin numbers in the bin variable, and summing the corresponding values of y.
I think you are close to your final solution.
Adam
Adam on 26 Aug 2014
Hi ,
Thanks. My data points are symmetric (Fig.1) but when I bin these data using the previous code I obtain another data which are not perfectly symmetric (Fig. 2). Do you know why ? I kindly appreciate your help.
the cyclist
the cyclist on 26 Aug 2014
I suppose it is either
  • the way the bin edges are defined, they are not centered around zero, OR
  • the way MATLAB treats values that are exactly on the bin edge, it consistently puts them to one side, leading to asymmetry.
laura9510
laura9510 on 31 Jan 2017
Jumping in years later but if I was looking to average within bins, is using accumarray possible in conjunction with another function?

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Asked:

on 5 Aug 2014

Commented:

on 31 Jan 2017

Community Treasure Hunt

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

Start Hunting!