Random permutation of integers
p = randperm( returns a row vector
containing a random permutation of the integers from 1 to
Random Permutation of Integers
Generate a random permutation of the integers from 1 to 6. The input to
randperm indicates the largest integer in the sampling interval (the smallest integer in the interval is 1).
r = randperm(6)
r = 1×6 6 3 5 1 2 4
Permute a Selection of Integers
Generate a random permutation of four unique integers (without repeating elements) selected randomly from the integers 1 to 8.
r1 = randperm(8,4)
r1 = 1×4 6 4 7 3
Generate another random permutation of four unique integers.
r2 = randperm(8,4)
r2 = 1×4 8 7 5 4
Control Random Number Generation
Save the current state of the random number generator and create a random permutation of the integers from 1 to 8.
s = rng; r = randperm(8)
r = 1×8 6 3 7 8 5 1 2 4
Restore the state of the random number generator to
s, and then create a new random permutation of the integers from 1 to 8. The permutation is the same as before.
rng(s) r1 = randperm(8)
r1 = 1×8 6 3 7 8 5 1 2 4
You can use the
rng function to specify the settings of the random number generator.
n — Number of integers in sample interval
Number of integers in sample interval, specified as a positive integer.
randperm permutes integer values from 1 to
k — Number of selected integers
Number of selected integers, specified as a positive integer.
must also be less than or equal to
The sequence of numbers produced by
randpermis determined by the internal settings of the uniform pseudorandom number generator that underlies
randperm. To control that shared random number generator, use the
The arrays returned by
randpermcontain permutation of integers without repeating integer values. This behavior is sometimes referred to as sampling without replacement. If you require repeating values, use the
randperm(n,n)both generate permutations of the integers 1 through
n, but they can give different random orderings in the permutations. For large
randperm(n,n)is faster than
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
To run this function on a GPU, use the syntax
p = gpuArray.randperm(n).
The two-input syntax is not supported.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Introduced before R2006a