Milind Anantwar
Milind Anantwar

Reputation: 82241

How to generate unique random numbers in Matlab?

I need to generate m unique random numbers in range 1 to n. Currently what I have implemented is:

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

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

Upvotes: 5

Views: 9945

Answers (5)

A. Kalabogia
A. Kalabogia

Reputation: 1

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

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

Upvotes: -1

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

The randperm approach described by @Stewie appears to be the way to go in most cases. However if you can only use Matlab with 1 input argument and n is really large, it may not be feasible to use randperm on all numbers and select the first few. In this case here is what you can do:

  1. Generate an integer between 1 and n
  2. Generate an integer between 1 and n-1, this is the choice out of the available integers.
  3. Repeat until you have m numbers

This can be done with randi and could even be vectorized by just drawing a lot of random numbers at each step until the unique amount is correct.

Upvotes: 4

Stewie Griffin
Stewie Griffin

Reputation: 14939

You can use randperm.

From the description:

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

Thus, randperm(6,3) might be the vector

[4 2 5]

Update

The two argument version of randperm only appeared in R2011b, so if you are using an earlier version of MATLAB then you will see that error. In this case, use:

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

Upvotes: 17

user664303
user664303

Reputation: 2063

Use Shuffle, from the MATLAB File Exchange.

Index = Shuffle(n, 'index', m);

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112749

As pointed out above, in Matlab versions older than R2011b randperm only accepts one input argument. In that case the easiest approach, assuming you have the Statistics Toolbx, is to use randsample:

randsample(n,m)

Upvotes: 5

Related Questions