How do I create discrete intervals, sum relevant data and produce a histogram?

I want to create a histogram. I have two variables x and y. I want the data to be binned into regular intervals based on x values, but frequency to be calculated as the sum of Y for all X values in each interval.
Example data
if true
% code
end
Y= [1, 1.1, 1.8, 0.7, 1.2, 1.7, 0.1]
X= [15, 21, 12, 24, 5, 34, 38 ]
We sort by X and place into discrete intervals of 0-10,10-20,20-30,30-40 We then sum the Y values within the intervals defined by X
if true
% code
end
For x=0-10 Sum
1.2 = 1.2
For x=10-20
1.8 + 1 = 2.8
For x=20-30
1.1 + 0.7 =1.8
For x=30-40
1.7+0.1 =1.8
Then plot/histogram interval vs sum of y
end
Thank you in advance!!

2 Comments

When you use the {} Code button it inserts some sample code like this:
if true
% code
end
but actually you do not need to keep this: all you need are the two spaces at the start of each line. You can edit your question and remove those superfluous lines of code and it makes your code easier to read because it is less confusing!
this is utterly invaluable advice Many, many thanks for sharing this.

Sign in to comment.

 Accepted Answer

Y= [1, 1.1, 1.8, 0.7, 1.2, 1.7, 0.1];
X= [15, 21, 12, 24, 5, 34, 38 ];
[~,ii] = histc(X,[0:10:30,inf]);
out = accumarray(ii(:),Y(:));

2 Comments

Hi,
I have a follow up question. How do I performed the histogram plot with the summed value? I don't think "histogram(out)" makes the trick...

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!