3 methods to group data and compute mean for each group
Each method deals with empty bins differently.
discretize + splitapply
Use discretize to group each value into the bins used in histogram and then splitapply to compute the mean for each group. Note that each bin must contain at least one data point. Example: compute the mean of data in bins defined by edges.
binID = discretize(data,edges)
binID =
9 10 2 10 7 1 3 6 10 10 2 10 10 5 9 2 5 10 8 10 7 1 9 10 7 8 8 4 7 2
a = splitapply(@mean,data,binID)
a =
5.3838 15.2780 26.0259 35.6310 46.5284 55.4195 66.1338 75.5438 83.3041 94.1885
discretize + groupsummary
Use discretize to group each value into the bins and then groupsummary to compute the mean of each group. When working with vectors, the first two arguments must be column vectors. Note that the output vector skips empty bins. See additional outputs to groupsummary to identify which bins are represented in the first output.
s = groupsummary(data(:),binID(:),'mean')
s =
5.3838
15.2780
26.0259
35.6310
46.5284
55.4195
66.1338
75.5438
83.3041
94.1885
discretize + accumarray
Use discretize to group each value into the bins and then accumarray to compute the mean of all bins. Note that empty bins are represented by a 0.
m = accumarray(binID(:),data,[],@mean)
m =
5.3838
15.2780
26.0259
35.6310
46.5284
55.4195
66.1338
75.5438
83.3041
94.1885
Comparison of these methods when some bins are empty
binID = discretize(data, edges);
m = accumarray(binID,data,[],@mean)
m =
0
0
8.4699
10.1766
12.7170
s = groupsummary(data,binID(:),'mean')
a = splitapply(@mean,data,binID)
Error using splitapply
For N groups, every integer between 1 and N must occur at least once in the vector of group numbers.