3

可能重复:
生成具有给定概率matlab的随机数

我需要创建一个随机分配数字 1、2 和 3 的列向量。但是我需要能够控制每个 oif 这三个数字的出现百分比。

例如,我有一个100 x 1列向量,我希望随机分配 30 个数字 1、50 个数字 2 和 20 个数字 3。

4

2 回答 2

4

我不确定您是否可以使用randrandi功能来做到这一点。

也许你可以写一个像这样的小模块:

bit1 = 1 * ones(1,20);
bit2 = 2 * ones(1,50);
bit3 = 3 * ones(1,30);

bits = [bit1 bit2 bit3];
randbits = bits(:, randperm(length(bits)))
于 2013-01-15T07:32:39.800 回答
1

您可以使用每个数字的百分比的CDF(累积分布函数)来做到这一点。

pdf = [ 30 50 20 ]/100; % the prob. distribution fun. of the samples
cdf = cumsum( pdf );
% I assume here all entries of the PDF are positive and sum(pdf)==1
% If this is not the case, you may normalize pdf to sum to 1.

采样本身

n = 100; % number of samples required
v = rand(n,1); % uniformly samples
tmp = bsxfun( @le, v, cdf );
[~, r] = max( tmp, [], 2 );

正如@Dan 所观察到的(见下面的评论),最后一行可以替换为

r = numel(pdf) + 1 - sum( tmp, 2 );

该向量r是整数的随机向量,1,2,3应满足所需的pdf

于 2013-01-15T07:30:10.477 回答