Search code examples
matlabunique

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?


Solution

  • 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);