Matrix probability with just one 1

조회 수: 1 (최근 30일)
Marcos Ortego
Marcos Ortego 2020년 7월 1일
댓글: Marcos Ortego 2020년 7월 1일
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