[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Randomly generate 10 different integers

From: Pablo
Subject: Re: Randomly generate 10 different integers
Date: Mon, 14 Sep 2009 21:16:29 -0400
User-agent: Mozilla-Thunderbird (X11/20090707)

Rob Mahurin wrote:
> On Jun 30, 2009, at 1:45 PM, Xin Dong wrote:
>> I wanna randomly generate 10 different integers in a given range. I  
>> know I can use random function and discard duplicate values. But is  
>> there any other simple way to do it?
> One way is
>       [junk, index] = sort(rand(1,10));
>       disp(index)
> Rob

I had to do this recently. The above example just gives a random
permutation of the numbers 1 to 10 (the randperm function does exactly
that). To get N random numbers from dmin to dmax you sholud do:
D = randperm(dmax - dmin + 1);
D = D(:,1:N);
D = D + dmin - 1;

This is not very efficient if you need to select very few numbers, or
almost all, from a very large range, because I was not interested in the
order of the numbers, and you have to sort every number of the range.

If you have a very large range (I used randperm(10000), and it gets VERY
slow!) you might replace the above with a custom sort function, that
only sorts the first N numbers. That way, you can shave off a LOT of time.

I know this comes a little late, but it might still help somebody!


reply via email to

[Prev in Thread] Current Thread [Next in Thread]