how to generate permutations of N numbers in K positions

72 ビュー (過去 30 日間)
Ali Danish 2019 年 2 月 19 日

I want to generate all permutations of N numbers in K places, where K is less than N (nPk) in matlab, I've searched online and already existing questions but couldn't find a functions which generates such permutations without repitition. There are some functions which do this with repitation.
For example if I've a vector [1 2 3 4] my N is 4 and my K is 2, then I want 12 permutations using the formula N!/(N-K)1 = 4!/(4-2)! = 12
[1,2]
[1,3]
[1,4]
[2,1]
[2,3]
[2,4]
[3,1]
[3,2]
[3,3]
[4,1]
[4,2]
[4,3]
These are the permutations which I want to generate. Kindly suggest me the solution.

サインインしてコメントする。

回答 (3 件)

Stephen 2019 年 2 月 19 日

and use it like this:
>> sortrows(combinator(4,2,'p'))
ans =
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3
If you want to apply this to a vector that is not 1:N, simply use the output of combinator as indices into your vector.
0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Bruno Luong 2021 年 3 月 22 日

No loop, no extrenal file needed
N=5; K=3;
P=nchoosek(1:N,K);
P=reshape(P(:,perms(1:K)),[],K)
You might further sort the permutation so that the order is easily to follow
P = sortrows(P)
0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Sergey Kasyanov 2021 年 3 月 22 日
Hello!
Use nchoosek function with combination of perms function. That solution is slow but does not require any side files.
res = nchoosek(1:4, 2);
for i = 1:size(res,1)
res = [res; perms(res(i,:))];
end
res = unique(res, 'rows');

サインインしてコメントする。

R2013b

Community Treasure Hunt

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

Start Hunting!

Translated by