Permute matrix elements across rows

조회 수: 2 (최근 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 CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by