From: "Jan Simon" <>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Randperm, Randi, and Shuffle
Date: Sat, 18 Dec 2010 21:44:05 +0000 (UTC)
Organization: Universit&#228;t Heidelberg
Lines: 20
Message-ID: <iej9v5$g95$>
References: <iaq1os$sak$> <idpcig$7a8$> <idqqm6$rdv$> <idr6uj$n9r$> <idti1v$55l$> <ie3rq4$s92$> <ie40uc$hcp$> <ie8jup$2o4$> <ied3ek$qtt$> <iehv8o$kdf$>
Reply-To: "Jan Simon" <>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1292708645 16677 (18 Dec 2010 21:44:05 GMT)
NNTP-Posting-Date: Sat, 18 Dec 2010 21:44:05 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 869888
Xref: comp.soft-sys.matlab:696611

Dear Derek,

> function p = GenRandPermVecd(n)
> p = 1:n;
> r = 1 + floor( rand(n,1).*(1:n)' );

You got me. I tried exactly the same and got the same slowdown of 10%.
A drawback is the memory consumption:
  1. p = 1:n;   % n doubles
  2. a = rand(n,1)  % n doubles
  3. b = 1:n  % n doubles  (should reuse p here)
  4. c = (a * b)  % n doubles
  5. d = floor(c)  % n doubles
  6. r = 1 + d  % n doubles

Sme of the temporarily used memory will be used twice, but without the JIT acceleration this will so much time, that the actually faster vectorized call of RAND does not accelerate the complete program.

I'd be interested in the timing of a corresponding Fortran77 Mex function. I've been very impressed each time I see the speed of naively implemented  matrix matrix multiplications in Fortran compared to damn tricky unrolled loop pointer based C versions.

Kind regards, Jan