randperm

Random permutation of integers

Description

example

p = randperm(n) returns a row vector containing a random permutation of the integers from 1 to n without repeating elements.

example

p = randperm(n,k) returns a row vector containing k unique integers selected randomly from 1 to n.

p = randperm(s,___) generates a random permutation of integers from random number stream s instead of the default global stream. To create a stream, use RandStream. Specify s followed by any of the argument combinations in previous syntaxes.

Examples

collapse all

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

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

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.

Input Arguments

collapse all

Number of integers in sample interval, specified as a positive integer. randperm permutes integer values from 1 to n inclusive.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Number of selected integers, specified as a positive integer. k must also be less than or equal to n.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Random number stream, specified as a RandStream object.

Example: s = RandStream('dsfmt19937'); randperm(s,10)

Tips

• The sequence of numbers produced by randperm is determined by the internal settings of the uniform pseudorandom number generator that underlies rand, randi, randn, and randperm. To control that shared random number generator, use the rng function.

• The arrays returned by randperm contain permutation of integers without repeating integer values. This behavior is sometimes referred to as sampling without replacement. If you require repeating values, use the randi function.

• randperm(n) and randperm(n,n) both generate permutations of the integers 1 through n, but they can give different random orderings in the permutations. For large n, randperm(n,n) is faster than randperm(n).