Permute matrix elements across rows

4 visualizzazioni (ultimi 30 giorni)
Treli
Treli il 10 Feb 2011
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.

Risposta accettata

Sean de Wolski
Sean de Wolski il 10 Feb 2011
[xx yy zz] = ndgrid(X(:,1),X(:,2),X(:,3));
X3 = sortrows([xx(:), yy(:),zz(:)],[1 2 3]);
isequal(X2,X3)
% ans = 1
  1 Commento
Jos (10584)
Jos (10584) il 11 Feb 2011
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

Accedi per commentare.

Più risposte (2)

Jos (10584)
Jos (10584) il 11 Feb 2011
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 il 10 Feb 2011
Just what I needed! Many thanks tr

Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by