フィルターのクリア

how to generate permutations of N numbers in K positions

93 ビュー (過去 30 日間)
Ali Danish
Ali Danish 2019 年 2 月 19 日
コメント済み: Subzero 2023 年 3 月 31 日
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.

採用された回答

Stephen23
Stephen23 2019 年 2 月 19 日
編集済み: Stephen23 2019 年 2 月 19 日
Download Loginatorist's powerful FEX submission combinator:
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.

その他の回答 (2 件)

Bruno Luong
Bruno Luong 2021 年 3 月 22 日
編集済み: 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)
P = 60×3
3 2 1 4 2 1 5 2 1 4 3 1 5 3 1 5 4 1 4 3 2 5 3 2 5 4 2 5 4 3
You might further sort the permutation so that the order is easily to follow
P = sortrows(P)
P = 60×3
1 2 3 1 2 4 1 2 5 1 3 2 1 3 4 1 3 5 1 4 2 1 4 3 1 4 5 1 5 2
  4 件のコメント
Walter Roberson
Walter Roberson 2022 年 11 月 24 日
If you have an array P that is 2 or more dimensions (not a vector!), and you use P(A,B) where A and B might be arrays, then the result is the same as if you had used P(A(:), B(:)) -- so P(A(1),B(1)), P(A(2),B(1)), P(A(3),B(1)) up to P(A(end),B(1)) is the first column, then the second column would be P(A(1),B(2)), P(A(2),B(2)), P(A(3),B(2)) to P(A(end),B(2)), and so on -- all combinations of the elements in A with all of the elements in B, same as if A and B had been vectors rather than 2D arrays.
The shape of the result might be different if P is a vector instead of a 2D array.
Subzero
Subzero 2023 年 3 月 31 日
Thanks for explaining that. I get it now.

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


Sergey Kasyanov
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');
  1 件のコメント
Abdelrahman Mohamed
Abdelrahman Mohamed 2023 年 3 月 30 日
Thanks
Sergey Kasyanov
that is works

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2013b

Community Treasure Hunt

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

Start Hunting!

Translated by