randperm
Random permutation of the integers 1 to n.
Category: Mathematics > Random Number Generation
Syntax
p = randperm(n)
Returns a row vector with the integers 1 to n in random order.
p = randperm(n, k)
Returns k unique integers chosen at random from 1:n.
p = randperm(s, ___)
Uses the RandStream object s instead of the global stream.
Description
Every value appears at most once, so randperm samples without replacement. It is the usual way to shuffle: x(randperm(numel(x))) reorders a vector, and randperm(n, k) picks k random indices.
Input arguments
n- Nonnegative integer scalar.
k- Number of values to return, with
0 <= k <= n; otherwise it is an error.
Output arguments
p- Row vector of unique integers, every ordering equally likely.
Example
Shuffling and sampling
rng(1);
randperm(6)
randperm(10, 3)
x = [10 20 30 40];
x(randperm(4))
Output
ans = 1×6
3 6 5 4 1 2
ans = 1×3
2 4 9
ans = 1×4
40 20 10 30
Notes
The order produced for a given seed may differ from the one MATLAB gives.