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?
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]
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With