Matrix probability with just one 1

1 view (last 30 days)
Lets say I have the following matrix:
[0 0.5 0 0 0.5]
Meaning there is a probability of a 1 on the second or fifth position.
There can only be one 1 on this matrix, so there is only two posible outcomes:
[0 1 0 0 0] or [0 0 0 0 1]
I already solved this problem, but in a very long way, by dividing 1 by the probability (0.5 in this case) and then generate a random number between 1 and the result of the previous division (1 or 2 in this example), and then iterate through the indexes and enter the ones with probability, count them and then set one to 1 and the rest to 0.
I was thinking of a more elegant way to solve this, for example creating a new Matrix [1 1 1 1 1] and then use binornd between this matrix and the probability matrix, but this gives me four possible outcomes instead of two: [0 0 0 0 0], [ 0 1 0 0 0], [0 0 0 0 1] or [0 1 0 0 1].
Is there a way to use binornd or any other function to do what I want in a more elegant way?
Thanks!
  2 Comments
Rik
Rik on 1 Jul 2020
Are all the probabilities the same in your real application?
Marcos Ortego
Marcos Ortego on 1 Jul 2020
Is either two 1/2, or three 1/3 or four 1/4.

Sign in to comment.

Accepted Answer

Rik
Rik on 1 Jul 2020
This code only works for positions with equal probability.
dist=[0 0.5 0 0 0.5];
valid_pos=find(dist);%select non-zero
out=zeros(size(dist));
out(valid_pos(randi(end)))=1;

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!