Calculate median values of slices of array associated with histogram bins

3 ビュー (過去 30 日間)
dormant
dormant 2023 年 11 月 15 日
コメント済み: Star Strider 2023 年 11 月 15 日
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?

採用された回答

Star Strider
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)
binsums = 4×1
-13.0331 20.8357 -1.5279 -2.0722
binmedians = accumarray(idx+1, (1:numel(idx)).', [], @(x)median(array2(x)))
binmedians = 4×1
-0.0237 0.2213 0.1113 -1.0361
.
  2 件のコメント
dormant
dormant 2023 年 11 月 15 日
Thank you very much. Some of the values going into the median ar NaNs, but I can handle them.
Star Strider
Star Strider 2023 年 11 月 15 日
As always, my pleasure!
Use the missingflag option that works best for you.
One such:
binmedians = accumarray(idx+1, (1:numel(idx)).', [], @(x)median(array2(x),'omitmissing'))
There are several others.
.

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2023 年 11 月 15 日
I would use the groupsummary function with the grouping information from the idx variable.
If all you want is the bin numbers, you could also use the discretize function instead of histcounts.
  1 件のコメント
dormant
dormant 2023 年 11 月 15 日
Thanks you very much. I'll try this as well as the solution suggested by Star Strider.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Distribution Plots についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by