## nextperm(V, K)

version 3.0.0.0 (4.26 KB) by
Next (lexicographic) permutation of values

Updated 16 Mar 2018

W = nextperm(V) or W = nextperm(V,1) returns the next permutation of
the vector V using lexographic ordening of the values in V. If there
is no next permutation, W returns V sorted in lexographic ordening
The output W is a row vector.

W = nextperm(V, K), where K is vector of positive integers (>= 0),
returns the Kth next permutation(s). The output is matrix with numel(K)
rows. The rows of W are sorted according to K, that is, W(x,:) holds
the K(x)-th permutation of V.

This function may be useful to generate permutations one-by-one, when
the total number of permutations is too large to store them all in
memory.

Examples:
% call nextperm repeatedly
V = [1 2 3 4]
V = nextperm(V) % (#1) 1 2 4 3
V = nextperm(V) % (#2) 1 3 2 4
V = nextperm(V) % (#3) 1 3 4 2

% get specific next permutations
W = nextperm([1 2 3 4], [0 3 1]) % returns a matrix
% [ 1 2 3 4
% 1 3 4 2
% 1 2 4 3 ]

% last permutation -> original array
V = [10:-1:2 1] % the last permutation of 1:10
W = nextperm(V) % 1:10 (0th permutation of 1:10)

% lexicographic permutations of a random array
R = randperm(10) % a random permutation
Rnext = nextperm(R, 1:5) % the next 5 permutation

% non-unique values of V
V = [10 20 20 30]
x = nextperm(1:numel(V), 3) % 1 3 4 2
W1 = V(x) % 10 20 30 20
W2 = nextperm(V,3) % 20 10 20 30 (lexicographic)

% use indices to get the next permutation of cells and struct arrays
C1 = {'A', 'BB', 1:4}
x = nextperm(1:numel(C1))
C2 = C1(x) % {'A', 1:4 ,'BB'}

Notes:
1) The functionality of the second input of perms has changed since
version 3.0.
2) The matlab function PERMS generates all permutations at once and can
therefore only be used for small array sizes. Note the PERMS does not
returns the permutations in sorted order.
V = 1:3 ; % 3 distinct values -> 6 permutations
W1 = perms(V)
W2 = nextperm(V, 0:5)

permpos, nextpermpos, permn, nchoose2, nchoose (FileExchange)

### Cite As

Jos (10584) (2022). nextperm(V, K) (https://www.mathworks.com/matlabcentral/fileexchange/57429-nextperm-v-k), MATLAB Central File Exchange. Retrieved .

##### MATLAB Release Compatibility
Created with R2017b
Compatible with any release
##### Platform Compatibility
Windows macOS Linux