How to retrieve the indices of the values in each bin?
39 次查看(过去 30 天)
显示 更早的评论
I have a histogram with values from a vector A , spread into 30 bins. How can I get the indices of the values in A, that correspond to each bin?
Example:
A = [ 4 6 8 2 5 3 3]
bin number 4 contains [4 3 3]
so I want to have a vecor B containing the indices B = [1 6 7]
0 个评论
回答(1 个)
Walter Roberson
2021-10-10
The code could be slightly simpler if all of the bins were only one value wide.
A = randi(60, 1, 50)
edges = [1:2:60, inf]
[counts, ~, bins] = histcounts(A, edges)
B = accumarray(bins(:), reshape(1:numel(bins), [], 1), [], @(V){V.'})
3 个评论
Walter Roberson
2021-10-28
If accumarray() is giving you that error, then it implies that some value in your matrix A is less than the first value in your edges vector or greater than the last one. For example,
A = randi([-2 60], 1, 50)
edges = [1:2:60, inf]
[counts, ~, bins] = histcounts(A, edges)
B = accumarray(bins(:), reshape(1:numel(bins), [], 1), [], @(V){V.'})
See how the 5th bin number is 0, which corresponds to the bin for the input value 0 in A, and 0 is before the first value in edges . (It is not because A has negative or 0 entries: it is strictly to do with the fact that it has entries that are outside the range of the edges list.)
Walter Roberson
2021-10-28
Note that in the following code, any value in A that is outside the range of the edges will not have its index appear anywhere in B.
A = randi([-2 60], 1, 50)
edges = [1:2:60, inf]
[counts, ~, bins] = histcounts(A, edges)
valididx = reshape(find(bins), [], 1);
B = accumarray( reshape(bins(valididx), [], 1), valididx, [], @(V){V.'})
另请参阅
类别
在 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!