Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate unique random numbers in Matlab?

Tags:

unique

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?

like image 275
Milind Anantwar Avatar asked Feb 17 '14 13:02

Milind Anantwar


1 Answers

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);
like image 82
Stewie Griffin Avatar answered Oct 06 '22 02:10

Stewie Griffin