Matrix probability with just one 1

1 Ansicht (letzte 30 Tage)
Marcos Ortego
Marcos Ortego am 1 Jul. 2020
Kommentiert: Marcos Ortego am 1 Jul. 2020
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 Kommentare
Rik
Rik am 1 Jul. 2020
Are all the probabilities the same in your real application?
Marcos Ortego
Marcos Ortego am 1 Jul. 2020
Is either two 1/2, or three 1/3 or four 1/4.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
Rik am 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;

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by