필터 지우기
필터 지우기

Creating a random matrix with different probabilities

조회 수: 1 (최근 30일)
Stam Kavid
Stam Kavid 2018년 6월 1일
댓글: Stam Kavid 2018년 6월 1일
Hey, I have 4 situations, and each situation has a different probability to be happened. P(0) = 0.2 P(1) = 0.46 P(2) = 0.16 P(3) = 0.18
I want to create a matrix(52,1) with [0 3] but with inequal probabilities. A= randi([0 3],52,1); With this, the probability to be have number 0,1,2,3 is 25%. Can u help me out?
Thanks in advance.
  댓글 수: 1
Stephen23
Stephen23 2018년 6월 1일
Stam Kavid's "Answer" moved here:
A= randi([0 3],52,1);
limit=4;
W=zeros(size(A));
C=zeros(size(A));
k=1;
for i=1:length(A)
C(k)=C(k)+1;
if W(k)>=limit
k=k+1
end
W(k)=W(k)+A(i)
end
W(k+1:end)=[ ];
C(k+1:end)=[ ];
I want to know how many times the A exceed limit(4), but every time that exceed the limit for example A=5 i want to start with 5-4=1 over again, if A=6 6-4=2 etc. How can i do this one? Thanks in advance

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 6월 1일
편집: Stephen23 2018년 6월 1일
P = rand(52,1);
P = (P>0.2) + (P>0.66) + (P>0.82)
Note that the values used here are just cumsum([0.2,0.46,0.16]), i.e. [0.2, 0.2+0.46, 0.2+0.46+0.16]. If you wanted to automatically adjust for different input values then you could use cumsum and something like hist or discretize... but the idea is the same.
I tested this code on 1e6 iterations:
N = 1e6;
V = nan(52,N);
for k = 1:N
P = rand(52,1);
P = (P>0.2) + (P>0.66) + (P>0.82);
V(:,k) = P;
end
and got a distribution that matches what you requested:
>> cnt = histc(V(:),0:3)/(N*52)
cnt =
0.20002
0.46002
0.15995
0.18000
  댓글 수: 1
Stam Kavid
Stam Kavid 2018년 6월 1일
Thank you very much. I appreciate your effort a lot!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2018년 6월 1일
편집: Steven Lord 2018년 6월 1일
% Generate the vector of probabilities for each of your classes
p = [0.2 0.46 0.16 0.18];
% Cumulative probability vector
probabilityBins = cumsum([0 p]);
% Sample data
x = rand(1, 1e6);
% Bin each element of the sample data into the appropriate bin
% whose edges are in probabilityBins
D = discretize(x, probabilityBins, 0:3);
% Show the first 10 sample data points and their bins
[x(1:10); D(1:10)]
% Show that the probabilities are roughly what you'd expect
histogram(D, 'Normalization', 'probability')
% Turn on the grid to see how each bar matches its probability
yticks(sort(p))
grid on
I'd say that looks pretty good.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by