Path: news.mathworks.com!newsfeed-00.mathworks.com!ucberkeley!news-hog.berkeley.edu!tethys.csu.net!newshub.sdsu.edu!elnk-nf2-pas!newsfeed.earthlink.net!stamper.news.pas.earthlink.net!newsread3.news.pas.earthlink.net.POSTED!5f968bd6!not-for-mail From: ellieandrogerxyzzy@mindspring.com.invalid (Roger Stafford) Newsgroups: comp.soft-sys.matlab Subject: Re: How to generate different random numbers Message-ID: <ellieandrogerxyzzy-2905071214030001@dialup-4.232.0.71.dial1.losangeles1.level3.net> References: <ef58601.-1@webcrossing.raydaftYaTP> Organization: - Lines: 55 Date: Tue, 29 May 2007 19:14:03 GMT NNTP-Posting-Host: 4.232.0.71 X-Complaints-To: abuse@earthlink.net X-Trace: newsread3.news.pas.earthlink.net 1180466043 4.232.0.71 (Tue, 29 May 2007 12:14:03 PDT) NNTP-Posting-Date: Tue, 29 May 2007 12:14:03 PDT Xref: news.mathworks.com comp.soft-sys.matlab:411696 In article <ef58601.-1@webcrossing.raydaftYaTP>, "yunzhi cheng" <sjtu_yh@yahoo.com> 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 <us@neurol.unizh.ch> 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); else i2 = i2 + 1; i3 = i3 + (i3>=i1) + (i3>=i2-1); end 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