MATLAB: Permute matrix elements across rows

matrixpermute rows

Say I have a 2×3 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.

Best Answer

[xx yy zz] = ndgrid(X(:,1),X(:,2),X(:,3));
X3 = sortrows([xx(:), yy(:),zz(:)],[1 2 3]);
isequal(X2,X3)
% ans = 1