【发布时间】:2017-03-10 17:52:27
【问题描述】:
我知道如何在 Matlab 中生成一定范围内的随机数。我现在要做的是在有更多机会获得某些随机数的范围内生成随机数。
例如:我如何使用 Matlab 生成 0 到 2 之间的随机数,其中 50% 会小于 0.5?
要获得 0 到 2 之间的数字,我会使用 (2-0)*rand+0。我怎么能做到这一点,但生成的数字的一定百分比小于 0.5?有没有办法使用 rand 函数来做到这一点?
【问题讨论】:
我知道如何在 Matlab 中生成一定范围内的随机数。我现在要做的是在有更多机会获得某些随机数的范围内生成随机数。
例如:我如何使用 Matlab 生成 0 到 2 之间的随机数,其中 50% 会小于 0.5?
要获得 0 到 2 之间的数字,我会使用 (2-0)*rand+0。我怎么能做到这一点,但生成的数字的一定百分比小于 0.5?有没有办法使用 rand 函数来做到这一点?
【问题讨论】:
这是一个建议:
N = 10; % how many random numbers to generate
bounds = [0 0.5 1 2]; % define the ranges
prob = cumsum([0.5 0.3 0.2]); % define the probabilities
% pick a random range with probability from 'prob':
s = size(bounds,2)-cumsum(bsxfun(@lt,rand(N,1),prob),2);
% pick a random number in this range:
b = rand(1,N).*(bounds(s(:,end)+1)-bounds(s(:,end)))+bounds(s(:,end))
这里我们有prob(k) 的概率在bounds(k) 到bounds(k+1) 之间抽取一个数字。基本上,我们首先绘制一个具有定义概率的范围,然后从该范围中绘制另一个数字。所以我们只对b感兴趣,但在途中需要s(主要是为了以矢量化的方式创建大量数字)。
所以我们得到:
b =
Columns 1 through 5
0.5297 0.15791 0.88636 0.34822 0.062666
Columns 6 through 10
0.065076 0.54618 0.0039101 0.21155 0.82779
或者,对于N = 100000,我们可以绘制:
所以我们可以看到值是如何在bounds 中的 3 个范围之间分布的。
【讨论】:
您可以使用多项分布来绘制范围,然后计算随机数。方法如下:
N = 10;
bounds = [0 0.5 1 2]; % define the ranges
d = diff(bounds);
% pick a N random ranges from a multinomial distribution:
s = mnrnd(N,[0.5 0.3 0.2]);
% pick a random number in this range:
b = rand(1,N).*repelem(d,s)+repelem(bounds(1:end-1),s)
所以你得到s:
s =
50 39 11
表示您从第一个范围中获取 50 个值,从第二个范围中获取 39 个值,依此类推...
你在b得到了结果:
b =
Columns 1 through 5
0.28212 0.074551 0.18166 0.035787 0.33316
Columns 6 through 10
0.12404 0.93468 1.9808 1.4522 1.6955
所以基本上它与我在这里发布的第一种方法相同,但它可能更准确和/或可读性更高。另外,我没有测试哪种方法更快。
【讨论】: