说我想要1到10之间的5个数字。但是,我不希望重复任何数字。我该怎么做?
我想过做
randi([1,length(a)])
或者这个:
(10-1).*rand(5,1) + 1
但是,这只能一次给我一个号码!我想要唯一的数字,这将保证它。
答案 0 :(得分:1)
一种方法是使用randperm
:
N = 10; % Numbers from 1 to N will be permuted
n = 5; % Numbers to be extracted
x = randperm(N); % Permute numbers between 1 and N
x = x(1:n); % Retain first n
这可以推广到任何一组值:
N = 10; % Length of vector of N numbers to be permuted
y = randn(N, 1); % Vector from which you want to extract values
n = 5; % Numbers to be extracted
x = randperm(N); % Permute numbers between 1 and N
x = y(x(1:n)); % Retain first n of y
问题是当N很大而n很小时:
tic
N = 1e7;
n = 2;
x = randperm(N);
x = x(1:n);
toc
然后你需要找到一个更好的解决方案。如果您有统计工具箱,请尝试:
tic
x = randsample(N, n, false);
toc
另一种方法,也很慢,但没有使用randperm
或randsample
:
N = 1e7;
n = 2;
y = randn(N, 1);
tic
x = randn(N, 1);
[x x] = sort(x);
x = y(x(1:n));
toc