Reputation: 82241
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
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
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:
n
n-1
, this is the choice out of the available integers.m
numbersThis 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
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]
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
Reputation: 2063
Use Shuffle, from the MATLAB File Exchange.
Index = Shuffle(n, 'index', m);
Upvotes: 2
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