Using Accumarray to calculate the number of times data has fallen into a bin

4 views (last 30 days)
Currently having a problem where I have my data variables on the LHS and the bin into which they fall on the RHS. Z is the array below with two columns. I is the number of datum (this is only a small section of Z).
45.9267 13.0000
46.1661 14.0000
46.0204 13.0000
46.0314 13.0000
45.9924 13.0000
45.9579 13.0000
45.8643 13.0000
45.4999 12.0000
45.5909 12.0000
45.4622 12.0000
45.5962 12.0000
45.8968 13.0000
45.9769 13.0000
45.7437 13.0000
45.9199 13.0000
46.1198 14.0000
46.0863 13.0000
46.3141 14.0000
46.6091 15.0000
46.3690 14.0000
46.3833 14.0000
45.7627 13.0000
46.5289 14.0000
45.5311 12.0000
47.0671 15.0000
48.1886 18.0000
The values in the right hand column are the bins in which the number in the left hand column lie.
I then have:
Z = X(1:I,2);
pieces_of_data_in_bin = accumarray(Z,1);
pieces_of_data_in_bin =
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
3
I'm not sure whether this is what I want...I basically want to have an array with [1:number of bins] on the LHS and then the number of times data has fallen into each bin on the RHS. How would I go about doing this as currently the pieces_of_data_in_bins is only showing 16 numbers, not 18 (total number of bins...).
What's going wrong?
Thanks! :)

Accepted Answer

Star Strider
Star Strider on 23 Jul 2019
You are very close. You likely need to use the unique function with ‘Z’ so the bins and their counts are correctly aligned.
Try this:
Z = X(:,2);
[Zu,~,Zx] = unique(Z);
pieces_of_data_in_bin = accumarray(Zx,1);
Out = [Zu, pieces_of_data_in_bin]
producing:
Out =
12 5
13 12
14 6
15 2
18 1
The bin numbers are in the first column, and the counts are in the second column.
  13 Comments
Sophie Chumas
Sophie Chumas on 23 Jul 2019
Basically I'm now trying to use the Out values to define probability:
probability = (Out(:,2)/I); where I is the number of pieces of data i.e. rows...
but this produces this: which must be wrong since probability <1...
1.2222
1.2222
1.2222
3.6667
1.2222
0
0
0
0
0
0
2.4444
Star Strider
Star Strider on 23 Jul 2019
The denominator should not be the number of rows, but the total of ‘Out(:,2)’, so:
probability = Out(:,2)/sum(Out(:,2))
That is how I would define it.
Since it creates a vector result, if you want, you can concatenate it with ‘Out’ as either:
Out = [Out, probability];
or:
Out(:,3) = probability;
as you wish.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!