permn

Permutations with repetition, all or a subset
19K Downloads
Updated 10 Jan 2019

View License

permn - permutations with repetition
Using two input variables V and N, M = permn(V,N) returns all
permutations of N elements taken from the vector V, with repetitions.
V can be any type of array (numbers, cells etc.) and M will be of the
same type as V. If V is empty or N is 0, M will be empty. M has the
size numel(V).^N-by-N.

When only a subset of these permutations is needed, you can call permn
with 3 input variables: M = permn(V,N,K) returns only the K-ths
permutations. The output is the same as M = permn(V,N) ; M = M(K,:),
but it avoids memory issues that may occur when there are too many
combinations. This is particulary useful when you only need a few
permutations at a given time. If V or K is empty, or N is zero, M will
be empty. M has the size numel(K)-by-N.

[M, I] = permn(...) also returns an index matrix I so that M = V(I).

Examples:
M = permn([1 2 3],2) % returns the 9-by-2 matrix:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

M = permn([99 7],4) % returns the 16-by-4 matrix:
99 99 99 99
99 99 99 7
99 99 7 99
99 99 7 7
...
7 7 7 99
7 7 7 7

M = permn({'hello!' 1:3},2) % returns the 4-by-2 cell array
'hello!' 'hello!'
'hello!' [1x3 double]
[1x3 double] 'hello!'
[1x3 double] [1x3 double]

V = 11:15, N = 3, K = [2 124 21 99]
M = permn(V, N, K) % returns the 4-by-3 matrix:
% 11 11 12
% 15 15 14
% 11 15 11
% 14 15 14
% which are the 2nd, 124th, 21st and 99th permutations
% Check with permn using two inputs
M2 = permn(V,N) ; isequal(M2(K,:),M)
% Note that M2 is a 125-by-3 matrix

% permn can be used generate a binary table, as in
B = permn([0 1],5)

NB Matrix sizes increases exponentially at rate (n^N)*N.

See also perms, nchoosek
allcomb, permpos on the File Exchange

Cite As

Jos (10584) (2024). permn (https://www.mathworks.com/matlabcentral/fileexchange/7147-permn), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2018a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Linear Algebra in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
6.2.0.0

fixed coding style warnings

6.1.0.0

spelling corrections
Incorporated the functionality of permnsub, allowing for returning a subset rather than all permutations as well.

5.1.0.0

Renamed file into PERMN, fixed small bug, extended help section

1.3.0.0

Reference to COMBNSUB for large combinatorial problems.

1.2.0.0

corrected to give column vector output for N=1. (error pointed out by Wilson via email).

1.1.0.0

modified slightly based on suggestions by Jan Simon (thanks!)

1.0.0.0

fast algorithm