开发者

Using randi in MATLAB to get random values: values are not distributed uniformly

开发者 https://www.devze.com 2023-04-12 19:42 出处:网络
I am generating a random population of strings made of 0s and 1s. I am using randi(2)-1 to get a randomly generated single value 0 or 1. I expect to get 1s almost as frequently as 0s. Instead, when I

I am generating a random population of strings made of 0s and 1s. I am using randi(2)-1 to get a randomly generated single value 0 or 1. I expect to get 1s almost as frequently as 0s. Instead, when I view all the individuals in the population, they mostly consist of 1s. Below is the code - what is wrong?

for iInd=1:individualsCount
    individual(attrCount) = 0;

    for i=1:attrCount
         individual(i) = rand开发者_C百科i(2)-1;
    end

    population{iInd} = individual;
end


Firstly, you don't need a loop to generate a random string of 0's and 1's. Try this instead:

individual = randi([0 1],[attrCount,1]);

Secondly, again, you don't need a loop to construct your population cell. Try this instead:

population=arrayfun(@(x)randi([0 1],[attrCount,1]),1:individualsCount,'UniformOutput',false)

You might have to change the order of rows and columns depending on how you want to set it up.


Now, coming to your question, you ought to understand that these distributions are stochastic and approach a truly uniform distribution of 50% 1s and 50% 0s only as your sample size approaches infinity. If your attrCount is small enough, do not be surprised if you don't find numbers close to 50% for each. That doesn't mean it is wrong. It is what it is.

Here's how the distribution of 1s looks like for a random binary vector of different sample sizes. You can see that for small sample sizes, there is high variability (and by no means is this exact... it will be different each time), whereas as you start approaching large sample sizes of 1000 and above, your distribution of 1s gets closer and closer to 50%, eventually being exactly 50% at infinity.

Using randi in MATLAB to get random values: values are not distributed uniformly

0

精彩评论

暂无评论...
验证码 换一张
取 消