Description |
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 = PERMNSUB(V,N,K).
M will return only the K-ths permutations. The output is the same as M
= permn(V,N), followed by M = M(K,:), but it avoids memory issues by
generating all possible combinations first. This is particulary useful
when you only need one, or a small subset of all permutations at a
given time. If V or K is empty, or N is zerp, 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!' 'Ahello!'
'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:
% 1 1 2
% 5 5 4
% 1 5 1
% 4 5 4
% which are the 2nd, 124th, 21st and 99th combinations
% Check with permn
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
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 |