Creating a random matrix with different probabilities
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Stam Kavid
am 1 Jun. 2018
Kommentiert: Stam Kavid
am 1 Jun. 2018
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 Kommentar
Stephen23
am 1 Jun. 2018
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
Akzeptierte Antwort
Stephen23
am 1 Jun. 2018
Bearbeitet: Stephen23
am 1 Jun. 2018
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
Weitere Antworten (1)
Steven Lord
am 1 Jun. 2018
Bearbeitet: Steven Lord
am 1 Jun. 2018
% 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.
Siehe auch
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!