How do I produce all possible permutations of a vector, selecting a chosen number of elements?

25 ビュー (過去 30 日間)
Given some vector like a=[0:3] (but it doesn't have to be evenly spaced) I want to list all permutations (not combinations). I know perms can do this but it doesn't let you choose the number of elements you want.
I managed to do this choosing only 3 elements at a time using meshgrid. Here is my code for that:
%written in Octave
function C3 = ThreeNoteChordGen ()
%stores pitch classes 0 to 11
n=[0:11];
%initialize C3 as blank array;
C3=[];
[xx,yy,zz]=meshgrid(n,n,n);
[numRows, numCols, numPages] = size(zz);
for (countPage=1:numPages)
for (countCol=1:numCols)
newSegment=[zz(:,countCol,countPage), xx(:,countCol,countPage),yy(:,countCol,countPage)];
C3=[C3; newSegment];
endfor
endfor
endfunction
I'm having trouble adapting this method for choosing more elements at a time. I would appreciate any help. I'm very much a beginner programmer so I would rather you point me in the right direction rather than coding it for me (I probably won't understand your code);
Thank you
  1 件のコメント
Jeff Miller
Jeff Miller 2021 年 11 月 26 日
Check the answers here, especially the fileexchange function npermutek mentioned at the end.

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

採用された回答

Matt J
Matt J 2021 年 11 月 27 日
編集済み: Matt J 2021 年 11 月 27 日
a=[4,17,13,5,1,90];
n=3;
P=perms(1:n).';
b=nchoosek(a,n).' ;
out=reshape( b(P(:),:),n,[]).'
out = 120×3
13 17 4 13 4 17 17 13 4 17 4 13 4 13 17 4 17 13 5 17 4 5 4 17 17 5 4 17 4 5
  2 件のコメント
aweller3
aweller3 2021 年 11 月 27 日
Both of the solutions from Matt J and Jeff Miller work perfectly for that. Thank you. Is it possible to allow duplicates like [0 0 0;0 0 1;0 1 0]?
Matt J
Matt J 2021 年 11 月 28 日
Nothing in my solution forbids duplicates.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by