用给定的概率矩阵生成随机数 [英] Generate random number with given probability matlab

查看:120
本文介绍了用给定的概率矩阵生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以给定的概率生成一个随机数,但不确定如何:

I want to generate a random number with a given probability but I'm not sure how to:

我需要一个介于1到3之间的数字

I need a number between 1 and 3

num = ceil(rand*3);

但是我需要不同的值才能具有不同的生成概率.

but I need different values to have different probabilities of generating eg.

0.5 chance of 1
0.1 chance of 2
0.4 chance of 3

我敢肯定这很简单,但是我想不起来怎么做.

I'm sure this is straightforward but I can't think of how to do it.

推荐答案

简单的解决方案是生成具有均匀分布的数字(使用

The simple solution is to generate a number with a uniform distribution (using rand), and manipulate it a bit:

r = rand;
prob = [0.5, 0.1, 0.4];
x = sum(r >= cumsum([0, prob]));

或单线:

x = sum(rand >= cumsum([0, 0.5, 0.1, 0.4]));

说明

此处r是0到1之间的均匀分布的随机数.要生成1到3之间的整数,诀窍是将[0,1]范围划分为3个段,其中每个段的长度与其相应的概率成正比.就您而言,您将:

Explanation

Here r is a uniformly distributed random number between 0 and 1. To generate an integer number between 1 and 3, the trick is to divide the [0, 1] range into 3 segments, where the length of each segment is proportional to its corresponding probability. In your case, you would have:

  • 段[0,0.5),对应于数字1.
  • 段[0.5,0.6),对应于数字2.
  • 段[0.6,1],对应于数字3.

r落在任何细分中的概率与您希望每个数字的概率成正比. sum(r >= cumsum([0, prob]))只是将整数映射到段之一的一种理想方法.

The probability of r falling within any of the segments is proportional to the probabilities you want for each number. sum(r >= cumsum([0, prob])) is just a fancy way of mapping an integer number to one of the segments.

如果您对创建随机数矢量/矩阵感兴趣,可以使用循环或 arrayfun :

If you're interested in creating a vector/matrix of random numbers, you can use a loop or arrayfun:

r = rand(3); % # Any size you want
x = arrayfun(@(z)sum(z >= cumsum([0, prob])), r);

当然,还有矢量化解决方案,我太懒了,无法编写.

Of course, there's also a vectorized solution, I'm just too lazy to write it.

这篇关于用给定的概率矩阵生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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