Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Random Integers Within Specfic Ranges
Date: Sun, 13 Mar 2011 20:59:04 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 21
Message-ID: <iljb6o$fns$1@fred.mathworks.com>
References: <ildgd8$dhl$1@fred.mathworks.com> <ilfv5b$6pa$1@fred.mathworks.com> <ilg1cg$r6q$1@fred.mathworks.com> <ilgau4$5hb$1@fred.mathworks.com> <ilgfk4$4s1$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1300049944 16124 172.30.248.37 (13 Mar 2011 20:59:04 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sun, 13 Mar 2011 20:59:04 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: news.mathworks.com comp.soft-sys.matlab:715569

"Roger Stafford" wrote in message <ilgfk4$4s1$1@fred.mathworks.com>...
>   As you point out, Derek, randomly choosing from a selection of 2, then 3, then 4, etc. forces one to go all the way up to selecting from n.  Proceeding in the opposite direction from a selection of n, then n-1, and so forth allows the process to stop after only m steps, which is significant if m is appreciably less than n.
> ........
- - - - - - - - - -
  Derek, in my previous statement to you there was the tacit implication that the selection needs to use descending sizes to select from in order to work properly.  That is actually not the case.  It can go in either direction, from a k-index of n down to n-m+1 or else from n-m+1 up to n.  Either way all permutations of m out of n numbers are of equal probability in the final m elements of p.  This can easily be proved by mathematical induction on m for a fixed value of t=n-m.

  In other words the following works just as well as the previous code:

 p = a:b;
 n = length(p);
 for k = n-m+1:n
  q = ceil(k*rand);
  t = p(q);
  p(q) = p(k);
  p(k) = t;
 end
 p = p(n-m+1:n); % Use the last m elements in p

  It remains true however that starting at k = 1 or 2 will not work for general m out of n unless the iteration is continued up to k = n.

Roger Stafford