How do I create discrete intervals, sum relevant data and produce a histogram?
12 views (last 30 days)
Show older comments
tatyana gabellone
on 5 May 2015
Commented: Vlatko Milic
on 19 Dec 2022
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
Stephen23
on 5 May 2015
Edited: Stephen23
on 5 May 2015
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!
Accepted Answer
Andrei Bobrov
on 5 May 2015
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
Vlatko Milic
on 19 Dec 2022
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...
More Answers (0)
See Also
Categories
Find more on Histograms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!