如何在MATLAB中以已知的概率生成随机向量(0,1) [英] How do I generate a random vector (0,1) with a known probability in MATLAB

查看:615
本文介绍了如何在MATLAB中以已知的概率生成随机向量(0,1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码

operation=[rand(1,noOfNodes)>prob];

生成1和0(noOfNodes次).如果我使用prob=0.2并尝试100个值,则在某些情况下会存在40个零.是不是很奇怪?

to generate 1 and zeros (noOfNodes times). If I use prob=0.2 and try 100 values there exist in some cases 40 zeros. Isn't it weird?

我需要零值小于0.2的可能性

I need the probability of getting zeros less than 0.2

推荐答案

不,这并不奇怪.那是你的概率.

No, that's not weird. That's probability for ya.

如果掷硬币100次,您将不会总是获得50个正面和50个反面.有时您得到49和51,在极少数情况下甚至可以得到100次相同的结果.

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.

使用上面的代码,当noOfNodes为100时,不能保证总是得到20个零和80个.如果要生成一个向量,该向量始终具有20%的零,而总是零和一的随机排序,那么您可以使用 RANDPERM 像这样:

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

如果要生成零值在0%到20%之间的矢量,则可以使用函数

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));

这篇关于如何在MATLAB中以已知的概率生成随机向量(0,1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆