Matlab - calculating the probability of each element in a vector

I have a vector y , which can look like this:

y = [1 1 1 1 2 2 2 2 1 1 3 3 4 5]

And I want to bind the probability to every element inside y , since it would be generated by a random variable. In this case, element 1 will have a probability of 6/14, element 2 will have a probability of 4/14, element 3 will have a value of 2/14, and elements 4 and 5 will have a value of 1/14.

And basically, the result should look like this:

prob_y = 1/14 * [6 6 6 6 4 4 4 4 6 6 2 2 1 1]

Is there a way to do this without for or while chains?

+4
matlab
Aug 03 2018-11-21T00:
source share
3 answers

The unique elements of your input vector can be determined using the UNIQUE function. Then you can get the desired result using ARRAYFUN and an anonymous function that checks the amount of each unique element in your input vector:

 >> y = [1 1 1 1 2 2 2 2 1 1 3 3 4 5];
 >> prob_y = arrayfun (@ (x) length (find (y == x)), unique (y)) / length (y)

 prob_y =

     0.4286 0.2857 0.1429 0.0714 0.0714
+5
Aug 3 2018-11-11T00:
source share

Create a histogram with as many bins as the difference between your minimum and maximum elements (plus one to get the full range), and then normalize by dividing by the number of elements in the original vector.

Something like that:

 y = [1 1 1 1 2 2 2 2 1 1 3 3 4 5] p = hist(y, max(y) - min(y) + 1) / length(y) 

[Edit] To answer your updated question: use y to select indices from p , for example:

 prob_y = p(y) 
+2
Aug 03 2018-11-21T00:
source share

Here is an example using ACCUMARRAY :

 y = [1.3 1 1 1 2 2 2 2 1 1 3 3 4 5]; [g,~,gl] = grp2idx(y); count = accumarray(g,1); p = count(g) ./ numel(g) 

Probabilities:

 >> [y(:) p] ans = 1.3 0.071429 1 0.35714 1 0.35714 1 0.35714 2 0.28571 2 0.28571 2 0.28571 2 0.28571 1 0.35714 1 0.35714 3 0.14286 3 0.14286 4 0.071429 5 0.071429 

You can see a summary of the entries as:

 >> [gl count] ans = 1 5 1.3 1 2 4 3 2 4 1 5 1 

Note that I use GRP2IDX to handle cases like 1.3 or integers not starting with 1 .

+2
Aug 03 2018-11-11T00:
source share



All Articles