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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With