Random Permutation of Index Array
QUESTION: I wonder if any of you have an IDL function that gives a random permutation of an array index, or know of a straightforward way to compute it?
In Matlab such a function is called "randperm(n)" where n is the length of the array. For example, if one gives the integer 8, then it returns a length 8 integer array with values 0 to 7, randomly permutated.
It is not as simple as it sounds, since the indices are unique. I tried variations of randomly shifting indices (with SHIFT) from INDGEN with a random number generator, and the values were not "jumbled" satisfactorily.
ANSWER: Ken Bowman from the IDL newsgroup has provided an answer.
If I understand your question, you can just generate n uniform random variables and then sort the result.
IDL> x = LINDGEN(10) IDL> y = RANDOMU(dseed, 10) IDL> print, x 0 1 2 3 4 5 6 7 8 9 IDL> print, y 0.138249 0.0700486 0.310873 0.610514 0.332400 0.135694 0.975024 0.370555 0.763737 0.0268037 IDL> z = x[SORT(y)] IDL> print, z 9 1 5 0 2 4 7 3 8 6
Of course, written as a function, it would look something like this:
FUNCTION RandPerm, numberOfElements, SEED=seed x = Lindgen(numberOfElements) RETURN, x[Sort(Randomu(seed, numberOfElements))] END
Copyright © 2003 David W. Fanning
Last Updated 19 August 2003