Вопрос

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.

Это было полезно?

Решение

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top