How to create unique random numbers in matlab?

I need to generate m unique random numbers ranging from 1 to n. Currently, I have implemented the following:

round(rand(1,m)*(n-1)+1)

However, some numbers are repeated in the array. How can I get only unique numbers?

+4
source share
5 answers

You can use randperm.

From the description:

p = randperm(n,k) returns a row vector containing k unique integers randomly selected from 1 to n inclusive.

So it randperm(6,3) could be a vector

[4 2 5]

Update

Two arguments to the randperm version only appeared in R2011b, so if you are using an earlier version of MATLAB, you will see this error. In this case, use:

A = randperm(n); 
A = A(1:m);
+13

, Matlab R2011b randperm . , , Toolbx, randsample:

randsample(n,m)
+5

randperm, @Stewie, -, . , Matlab 1 n , , randperm . :

  • 1 n
  • 1 n-1, .
  • Repeat until you get mnumbers

This can be done with randiand even vectorized by simply drawing a lot of random numbers at each step until a unique amount is reached.

+4
source

Use the shuffle from the MATLAB file exchange file.

Index = Shuffle(n, 'index', m);
+1
source

This can be done by sorting a random vector of floats:

[i,i]=sort(rand(1,range));
output=i(1:m);
-1
source

Source: https://habr.com/ru/post/1527315/


All Articles