Matrix probability with just one 1

1 次查看(过去 30 天)
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 个评论
Rik
Rik 2020-7-1
Are all the probabilities the same in your real application?
Marcos Ortego
Marcos Ortego 2020-7-1
Is either two 1/2, or three 1/3 or four 1/4.

请先登录,再进行评论。

采纳的回答

Rik
Rik 2020-7-1
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;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by