Basic probability question

5 views (last 30 days)
lemontree45
lemontree45 on 5 Jul 2011
Could some please let me know the matlab command to generate a random sequence of 1 and 2 if the P(1)=0.6 and P(2)=0.4.
If we use the command 'randint(1,10,[1,2])' it generates 1,2 with equal probability.
Expecting a response soon. Thanks in advance
Regards

Accepted Answer

Daniel Shub
Daniel Shub on 5 Jul 2011
x = rand(1, 10); % Makes x have values between 0 and 1.
y = ones(size(x)); % Start off with all ones
y(x > 0.6) = 2; % Change all the values of y, for which x is greater than 0.6 to 2.

More Answers (4)

Oleg Komarov
Oleg Komarov on 5 Jul 2011
% Preallocate 1s
Out = ones(100,1);
% 40% shuld be 2s
num = round(numel(Out)*.4);
% Randomly scatter the 2s among the 1s
Out(randi([1 numel(Out)],num,1)) = repmat(2, num,1);

Royi Avital
Royi Avital on 5 Jul 2011
Uniform distribution is always a good point to start from. Then just divide the range [0 1] to whatever ratio you'd like according to the distribution you're after.
numElements = 100;
uniformDist = rand(numElements, 1);
outputDist = zeros(numElements, 1);
outputDist(uniformDist <= 0.6) = 1;
outputDist(uniformDist > 0.6) = 2;

lemontree45
lemontree45 on 5 Jul 2011
Thank you guys. so helpful

David Young
David Young on 5 Jul 2011
You can make a function that you can use instead of rand, like this:
p1 = 0.6; % probability of a 1 in the output
rand_special = @(m,n) (rand(m,n) > p1) + 1;
Then you can call the function to get an array of the size you want:
rand_special(1, 10)

Community Treasure Hunt

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

Start Hunting!