从向量中选择一定范围内的随机数

时间:2014-08-06 09:14:40

标签: matlab random

你如何使用randperm从一个向量中的5个范围中随机选择三个数字?

我有这样的矢量:

  

A = [1 2 3 4 5 6 7 8 9 10]

现在每隔5个连续值,我想随机挑选其中3个:

  

A_result = [1 3 5 6 7 9]

任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:1)

您可以使用reshaperandsample

rA = reshape( A, 5, [] ); % groups of 5 in a a row
A_result = rA( randsample( 5, 3, false ), : );
A_result = reshape( A_result, 1, [] );

答案 1 :(得分:1)

这个在每个5组中使用不同的随机索引。

A = [1 2 3 4 5 6 7 8 9 10]
B = reshape(A,5,[]) % (5 x 2)
ind = cell2mat(arrayfun(@(x)sort(randperm(5,3))',1:size(B,2),'UniformOutput',false)) % (3 x 2), row indices into B
ind = bsxfun(@plus,ind,size(B,1)*(0:size(B,2)-1)) % (3 x 2), linear indices into B
C = B(ind) % (3 x 2) result
C(:)' % result vector

每次sort(randperm(5,3))'调用都会生成一个随机列向量,其中包含从1到5的3个递增数字,如[1; 3; 4]或[2; 4; 5]。具有伪参数x的{​​{3}}在此示例中将此调用2次,因为A由2个长度为5的子向量组成。使用参数' Uniform output'设置为false,它会生成这些随机向量的单元格数组,cell2mat会将其转换为(3 x 2) - 矩阵indbsxfun调用将矩阵ind中的值转换为矩阵BA矩阵A = rand(900,25); % (900 x 25) B = A'; % (25 x 900) ind = cell2mat(arrayfun(@(x)sort(randperm(25,17))',1:size(B,2),'UniformOutput',false)); % (17 x 900), row indices into B ind = bsxfun(@plus,ind,size(B,1)*(0:size(B,2)-1)); % (17 x 900), linear indices into B C = B(ind); % (17 x 900), result

对于您的(900 x 25)矩阵,请执行

{{1}}

答案 2 :(得分:1)

您可以预先生成所有可能的拣选模式,然后为每个组随机选择一个这样的模式。这种方法适用于小组大小,否则可能会占用大量内存。

A = 1:10; %// example data
n = 5; %// group size. Assumed to divide numel(A)
k = 3; %// how many to pick from each group

S = numel(A);
patterns = nchoosek(1:n, k); %// all possible picking patterns
K = size(patterns, 1);
p = randi(K, S/n, 1); %// generate random indices for patterns
pick = bsxfun(@plus, patterns(p,:).', (0:n:S-1)); %'// to linear indices
A_result = A(pick(:));
相关问题