如何使用MATLAB程序创建随机排列为1、2和3的新列阵列?

如何使用MATLAB程序创建随机排列为1、2和3的新列阵列?,matlab,random,Matlab,Random,可能重复: 我需要创建一个列向量,其中包含数字1、2和3的随机赋值。但是,我需要能够控制这3个数字中每个oif的出现百分比 例如,我有一个100x1列向量,我想要随机分配数字1中的30个,数字2中的50个,数字3中的20个。你可以使用每个数字的百分比 pdf = [ 30 50 20 ]/100; % the prob. distribution fun. of the samples cdf = cumsum( pdf ); % I assume here all entries of th

可能重复:

我需要创建一个列向量,其中包含数字1、2和3的随机赋值。但是,我需要能够控制这3个数字中每个oif的出现百分比

例如,我有一个
100x1
列向量,我想要随机分配数字1中的30个,数字2中的50个,数字3中的20个。

你可以使用每个数字的百分比

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

我不确定是否可以使用
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)))

Is[~,r]=max(tmp,[],2);和4-sum(tmp,2)一样?@Dan-真的!很好的一个…谢谢,只是检查我理解为没有matlab在我身上。这是一个伟大的解决方案顺便说一句。嗨,谢谢。。。如果我需要进行30次随机试验呢。因此,我如何创建一个30x100矩阵,它有30个不同的随机序列,而不是重复随机命令30次。很抱歉,我对MATLAB还是很陌生。你必须在那个条件中使用循环。另一种方法是用一个(30,20)替换一个(1,20)。然后需要使用
horzcat
vertcat