Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - computing the probability of each element within a vector

Tags:

matlab

I am having a vector y which may have the following form:

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

And I want to attach a probability to each element within y as it would've been generated by a random variable. In this case, the element 1 would have the probability 6/14, the element 2 would have the probability 4/14, the element 3 the value 2/14 and the elements 4 and 5 the value 1/14.

And basically, the result should look like:

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

Is there a way of doing this without any for or while loops?

like image 650
Simon Avatar asked Jan 19 '23 01:01

Simon


1 Answers

The unique elements in your input vector can be determined using the UNIQUE function. You can then get the desired output using ARRAYFUN and an anonymous function that checks the number 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
like image 115
b3. Avatar answered Mar 04 '23 19:03

b3.