permutations and combinations of column

1 回表示 (過去 30 日間)
Jen-Yu Hsiao
Jen-Yu Hsiao 2012 年 9 月 10 日
If there are two matrices
A=[1 2 3 4];
B=[5 6 7 8];
How can I create this
C=[ 1 2 3 4;
1 2 3 8;
1 2 7 4;
1 2 7 8;
1 6 3 4;
1 6 3 8;
1 6 7 4;
1 6 7 8;
5 2 3 4;
5 2 3 8;
5 2 7 4;
5 2 7 8;
5 6 3 4;
5 6 3 8;
5 6 7 4;
5 6 7 8]

回答 (2 件)

Sean de Wolski
Sean de Wolski 2012 年 9 月 10 日
A=[1 2 3 4];
B=[5 6 7 8];
AB = [A;B];
idx = fullfact([2 2 2 2]);
C = AB(sub2ind([2 4],idx,repmat(1:4,size(idx,1),1)))
This won't be sorted. You could presort idx so that it is:
idx = sortrows(idx,1:4)
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 10 日
result=C(idx)
Sean de Wolski
Sean de Wolski 2012 年 9 月 11 日
@Azzi: That won't work because idx is only referencing the row in AB. We need the column information also. Of course, if speed is the primary goal, a for-loop will smoke sub2ind() and day of the week...

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


Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 10 日
編集済み: Azzi Abdelmalek 2012 年 9 月 10 日
A=[1 2 3 4];B=[5 6 7 8];
C=[];n=length(A);
for k=1:n
un=ones(2^(n-k),1);
C=[C repmat([A(k)*un; B(k)*un],2^(k-1),1)];
end

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by