Documentation

randperm

Random permutation of integers

Description

example

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

example

p = randperm(n,k)returns a row vector containingkunique integers selected randomly from 1 ton.

Examples

collapse all

Generate a random permutation of the integers from 1 to 6. The input torandpermindicates the largest integer in the sampling interval (the smallest integer in the interval is 1).

r = randperm(6)
r =1×66 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×46 4 7 3

Generate another random permutation of four unique integers.

r2 = randperm(8,4)
r2 =1×48 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×86 3 7 8 5 1 2 4

Restore the state of the random number generator tos, 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×86 3 7 8 5 1 2 4

You can use therngfunction to specify the settings of the random number generator.

Input Arguments

collapse all

Number of integers in sample interval, specified as a positive integer.randpermpermutes integer values from 1 toninclusive.

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

Number of selected integers, specified as a positive integer.kmust also be less than or equal ton.

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

Tips

  • The sequence of numbers produced byrandpermis determined by the internal settings of the uniform pseudorandom number generator that underliesrand,randi,randn, andrandperm. To control that shared random number generator, use therngfunction.

  • The arrays returned byrandpermcontain permutation of integers without repeating integer values. This behavior is sometimes referred to as sampling without replacement. If you require repeating values, use therandifunction.

  • randperm(n)randperm(n,n)both generate permutations of the integers 1 throughn, but they can give different random orderings in the permutations. For largen,randperm(n,n)is faster thanrandperm(n).

Extended Capabilities

C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.

Introduced before R2006a