Calculate median values of slices of array associated with histogram bins
7 次查看(过去 30 天)
显示 更早的评论
I have an array (array1) which I want to put into histogram bins. I have a second array (array2) which is the same length.
I can sum the values of array2 in each bin with this:
[count, edges, idx] = histcounts(array1,edges);
binsums = accumarray(idx,array2);
But how can I calculate the median values of array2 in each bin?
0 个评论
采纳的回答
Star Strider
2023-11-15
I would use another accumarray call:
binmedians = accumarray(idx+1, (1:numel(idx)).', [], @(x)median(array2(x)))
Creating data and correcting for ‘idx’ having 0 for some elements (making them inappropriate index values) —
array1 = randn(1E+3,1);
array2 = randn(1E+3,1);
edges = 1:9;
[count, edges, idx] = histcounts(array1,edges);
binsums = accumarray(idx+1,array2)
binmedians = accumarray(idx+1, (1:numel(idx)).', [], @(x)median(array2(x)))
.
2 个评论
Star Strider
2023-11-15
As always, my pleasure!
One such:
binmedians = accumarray(idx+1, (1:numel(idx)).', [], @(x)median(array2(x),'omitmissing'))
There are several others.
.
更多回答(1 个)
Steven Lord
2023-11-15
If all you want is the bin numbers, you could also use the discretize function instead of histcounts.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!