How to retrieve the indices of the values in each bin?
75 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Walter Roberson
on 10 Oct 2021
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 Comments
Walter Roberson
on 28 Oct 2021
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.'})
See Also
Categories
Find more on Annotations 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!