How do I generate a random vector (0,1) with a known probability in MATLAB
I am using the following code
operation=[rand(1,noOfNodes)>prob];
to generate 1 and zeros (noOfNodes
times). If I use prob=0.2
and try 100 values the开发者_如何转开发re exist in some cases 40 zeros. Isn't it weird?
I need the probability of getting zeros less than 0.2
No, that's not weird. That's probability for ya.
If you flip a coin 100 times, you don't always get 50 heads and 50 tails. Sometimes you get 49 and 51, and on that rarest of occasions you can even get the same one 100 times.
With your above code you're not guaranteed to always get 20 zeroes and 80 ones when noOfNodes
is 100. If you want to generate a vector that always has 20% zeroes, but with a random ordering of zeroes and ones, then you can accomplish this using the function RANDPERM like so:
operation = [zeros(1,20) ones(1,80)]; %# Fill the vector with 0 and 1
operation = operation(randperm(100)); %# Randomly reorder it
If you want to generate a vector that has anywhere from 0% to 20% zeroes, you can modify the code above using the function RANDI:
operation = [randi([0 1],1,20) ones(1,80)];
operation = operation(randperm(100));
精彩评论