MATLAB 中的加权随机数 [英] Weighted random numbers in MATLAB

查看:67
本文介绍了MATLAB 中的加权随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从向量a中随机选取N个数字,并为每个数字分配权重?

How to randomly pick up N numbers from a vector a with weight assigned to each number?

让我们说:

a = 1:3; % possible numbers
weight = [0.3 0.1 0.2]; % corresponding weights

在这种情况下,选择 1 的概率应该是选择 2 的 3 倍.

In this case probability to pick up 1 should be 3 times higher than to pick up 2.

所有权重的总和可以是任何值.

Sum of all weights can be anything.

推荐答案

R = randsample([1 2 3], N, true, [0.3 0.1 0.2])

randsample 包含在统计工具箱中

否则,您可以使用某种轮盘选择过程.请参阅此类似问题(虽然不是特定于 MATLAB 的).这是我的单行实现:

Otherwise you can use some kind of roulette-wheel selection process. See this similar question (although not MATLAB specific). Here's my one-line implementation:

a = 1:3;             %# possible numbers
w = [0.3 0.1 0.2];   %# corresponding weights
N = 10;              %# how many numbers to generate

R = a( sum( bsxfun(@ge, rand(N,1), cumsum(w./sum(w))), 2) + 1 )

说明:

考虑区间 [0,1].我们为列表中的每个元素 (1:3) 分配一个长度与每个元素的权重成正比的子区间;因此1得到长度0.3/(0.3+0.1+0.2)的区间,其他的一样.

Consider the interval [0,1]. We assign for each element in the list (1:3) a sub-interval of length proportionate to the weight of each element; therefore 1 get and interval of length 0.3/(0.3+0.1+0.2), same for the others.

现在如果我们生成一个在 [0,1] 上均匀分布的随机数,那么 [0,1] 中的任何数字都有相等的被选中的概率,因此子区间的长度决定了随机数的概率落在每个区间的数字.

Now if we generate a random number with uniform distribution over [0,1], then any number in [0,1] has an equal probability of being picked, thus the sub-intervals' lengths determine the probability of the random number falling in each interval.

这与我在上面所做的相符:选择一个数字 X~U[0,1](更像 N 数字),然后以矢量化的方式找出它落入哪个区间..

This matches what I'm doing above: pick a number X~U[0,1] (more like N numbers), then find which interval it falls into in a vectorized way..

可以通过生成足够大的序列N=1000来检查上述两种技术的结果:

You can check the results of the two techniques above by generating a large enough sequence N=1000:

>> tabulate( R )
  Value    Count   Percent
      1      511     51.10%
      2      160     16.00%
      3      329     32.90%

或多或少匹配归一化权重 w./sum(w) [0.5 0.16667 0.33333]

which more or less match the normalized weights w./sum(w) [0.5 0.16667 0.33333]

这篇关于MATLAB 中的加权随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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