How do I generate a random vector (0,1) with a known probability in MATLAB

回眸只為那壹抹淺笑 提交于 2019-12-01 19:28:22

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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!