生成具有范围的唯一随机Matlab数 [英] Generate Unique Random Matlab Numbers with a range
本文介绍了生成具有范围的唯一随机Matlab数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我想要1到10之间的5个数字.但是,我不想重复任何数字.我该怎么做?
Say I want 5 numbers between 1 to 10. However, I do not want any number to be repeated. How do I do this?
我想做
randi([1,length(a)])
或者这个:
(10-1).*rand(5,1) + 1
但是,这一次只能给我一个数字!我想要唯一的数字,这将无法保证.
But then, this only gives me one number at a time! I want unique numbers and this will nto guarantee it.
推荐答案
一种方法是使用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
这可以概括为任何一组值:
This can be generalized to any set of values:
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小时:
The problem is when N is large and n is small:
tic
N = 1e7;
n = 2;
x = randperm(N);
x = x(1:n);
toc
然后,您需要找到一个更好的解决方案.如果您有统计工具箱,请尝试:
Then you need to find a better solution. If you have the Statistics Toolbox, try:
tic
x = randsample(N, n, false);
toc
另一种方法,它也很慢,但是没有使用randperm
或randsample
:
Another approach, which is also slow but doesn't make use of randperm
or randsample
:
N = 1e7;
n = 2;
y = randn(N, 1);
tic
x = randn(N, 1);
[x x] = sort(x);
x = y(x(1:n));
toc
这篇关于生成具有范围的唯一随机Matlab数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文