Permute matrix elements across rows
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Sean de Wolski
on 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 Comment
Jos (10584)
on 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
More Answers (2)
Jos (10584)
on 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))
0 Comments
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!