我正在尝试找到n-by-n矩阵的所有组合而不重复.
例如,我有一个像这样的矩阵:
A = [321 319 322; ...
320 180 130; ...
299 100 310];
我想要以下结果:
(321 180 310)
(321 130 100)
(319 320 310)
(319 139 299)
(322 320 100)
(322 180 299)
我尝试过使用ndgrid,但它需要两次行或列.
最佳答案 这是一个更简单(原生)的解决方案,包含
perms
和
meshgrid
:
N = size(A, 1);
X = perms(1:N); % # Permuations of column indices
Y = meshgrid(1:N, 1:factorial(N)); % # Row indices
idx = (X - 1) * N + Y; % # Convert to linear indexing
C = A(idx) % # Extract combinations
结果是一个矩阵,每行包含不同的元素组合:
C =
321 180 310
319 320 310
321 130 100
319 130 299
322 320 100
322 180 299
此解决方案还可以缩短为:
C = A((perms(1:N) - 1) * N + meshgrid(1:N, 1:factorial(N)))