Generate Unique Random Matlab Numbers with a range

有些话、适合烂在心里 提交于 2019-12-02 16:51:52

问题


Say I want 5 numbers between 1 to 10. However, I do not want any number to be repeated. How do I do this?

I thought of doing

 randi([1,length(a)])

Or this :

 (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.


回答1:


One way to do it is by using 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

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

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


来源:https://stackoverflow.com/questions/20273394/generate-unique-random-matlab-numbers-with-a-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!