我试图找到一个 n×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
的更简单( native )解决方案和 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)))
关于matlab - matlab中矩阵的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13760851/