【发布时间】:2012-12-29 06:12:05
【问题描述】:
我需要创建一个随机分配数字 1、2 和 3 的列向量。但是我需要能够控制这 3 个数字中每个 oif 的出现百分比。
例如,我有一个100 x 1 列向量,我希望随机分配数字 1 的 30 个、数字 2 的 50 个和数字 3 的 20 个。
【问题讨论】:
我需要创建一个随机分配数字 1、2 和 3 的列向量。但是我需要能够控制这 3 个数字中每个 oif 的出现百分比。
例如,我有一个100 x 1 列向量,我希望随机分配数字 1 的 30 个、数字 2 的 50 个和数字 3 的 20 个。
【问题讨论】:
我不确定您是否可以使用 rand 或 randi 函数来做到这一点。
也许你可以写一个像这样的小模块:
bit1 = 1 * ones(1,20);
bit2 = 2 * ones(1,50);
bit3 = 3 * ones(1,30);
bits = [bit1 bit2 bit3];
randbits = bits(:, randperm(length(bits)))
【讨论】:
horzcat 或vertcat 连接数组
您可以使用每个数字的百分比的CDF (cumulative destribution function) 来做到这一点。
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
【讨论】: