Permute matrix elements across rows

4 ビュー (過去 30 日間)
Treli
Treli 2011 年 2 月 10 日
Say I have a 2x3 matrix, e.g.
X = [1 2 3;
4 5 6]
I would like to be able to create a new n x 3 matrix, where n is the number of all possible combinations of the column elements across rows.
In lack of a better description, here is what this new matrix would look like this:
X2 = [X(1,1) X(1,2) X(1,3);
X(1,1) X(1,2) X(2,3);
X(1,1) X(2,2) X(1,3);
X(1,1) X(2,2) X(2,3);
X(2,1) X(1,2) X(1,3);
X(2,1) X(1,2) X(2,3);
X(2,1) X(2,2) X(1,3);
X(2,1) X(2,2) X(2,3)];
I'm sure there is a better way of doing this than just indexing, but I can't seem to find one.

採用された回答

Sean de Wolski
Sean de Wolski 2011 年 2 月 10 日
[xx yy zz] = ndgrid(X(:,1),X(:,2),X(:,3));
X3 = sortrows([xx(:), yy(:),zz(:)],[1 2 3]);
isequal(X2,X3)
% ans = 1
  1 件のコメント
Jos (10584)
Jos (10584) 2011 年 2 月 11 日
This will not work in general. Try , for instance, with
X = [1 5 4 ; 2 6 3] ;
and X3 will not be the same as X2

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

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2011 年 2 月 11 日
I suggest to split the matrix into the elements you want to make combinations of using MAT2CELL
X = [2 4 1 ; 5 3 6] ; % a disordered matrix!
C = mat2cell(X, size(X,1), ones(1,size(X,2)))
and combine these cells, using, for instance ALLCOMB on the File Exchange: http://www.mathworks.com/matlabcentral/fileexchange/10064-allcomb
X2 = allcomb(C{:}) % done
or modify allcomb's engine using NDGRID, CAT and RESHAPE (but take special care of the order):
[C{:}] = ndgrid(C{end:-1:1})
X3 = reshape(cat(numel(C)+1,C{end:-1:1}),[],numel(C))
Directly passing the columns of X to allcomb (or to NDGRID, etc.) works as well, but is not as versatile, of course:
allcomb(X(:,1),X(:,2),X(:,3))

Treli
Treli 2011 年 2 月 10 日
Just what I needed! Many thanks tr

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by