Permute matrix elements across rows
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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)
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)
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))
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!