From: (Roger Stafford)
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to generate different random numbers
Message-ID: <>
References: <ef58601.-1@webcrossing.raydaftYaTP>
Organization: -
Lines: 55
Date: Tue, 29 May 2007 19:14:03 GMT
X-Trace: 1180466043 (Tue, 29 May 2007 12:14:03 PDT)
NNTP-Posting-Date: Tue, 29 May 2007 12:14:03 PDT
Xref: comp.soft-sys.matlab:411696

In article <ef58601.-1@webcrossing.raydaftYaTP>, "yunzhi cheng"
<> wrote:

> I have to generate three diffrent random integars between 1 and n.
> If I use
> round(rand(1,3)*(n-1)+1)
> maybe some of the three number are the same.
> I wonder if thre is better way except generating them one by one?
> thanks.

In article <ef58601.0@webcrossing.raydaftYaTP>, us <> wrote:

> yunzhi cheng:
> <SNIP a few rand ints evergreen...
> one of the many solutions
>      n=10;
>      m=3;
>      r=randperm(n);
>      r=r(1:m)
> us
  With only three distinct integers to generate, you may be interested in
the following alternative method if execution time is an issue, Yunzhi. 
It calls on 'rand' just three times instead of the n times required by
'randperm', and therefore ought be faster for large values of n, even
though it is less elegant-looking and uses more lines of code.  For n =
50, it is distinctly faster on my own machine.

 i1 = ceil(n*rand);
 i2 = ceil((n-1)*rand);
 i3 = ceil((n-2)*rand);
 if i2 < i1
  i3 = i3 + (i3>=i2) + (i3>=i1-1);
  i2 = i2 + 1;
  i3 = i3 + (i3>=i1) + (i3>=i2-1);

The quantities, i1, i2, and i3 are the three desired integers.  They are
always distinct and each may range from 1 to n.  The property of being
statistically uniformly distributed among all n*(n-1)*(n-2) possible
sequences of distinct integers from 1 to n is retained.

  Note:  This works with my ancient version (4a), but you might need to
convert the above logicals to doubles to make it work, that is,
double(i3>=i2), etc.

Roger Stafford