Matlab中矩阵的所有组合

4

我正在尝试查找一个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,但它会将行或列重复。

请包含一些代码以展示你尝试过什么 - Serge Belov
3个回答

2
这是一个更简单的(本地)解决方案,使用permsmeshgrid
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)))

0

ALLCOMB 是你问题的关键。

例如,我现在不在 MATLAB 机器前面,所以我从网上找了一个示例。

x = allcomb([1 3 5],[-3 8],[],[0 1]) ;
ans
1 -3 0
1 -3 1
1 8 0
...
5 -3 1
5 8 0
5 8 1

如果您将allcomb的参数输入为给定矩阵的行,则会导致重复的列,这不是所需的。 - mythealias

0

您可以使用perms来按如下方式排列列:

% A is given m x n matrix
row = 1:size( A, 1 );
col = perms( 1:size( A, 2 ) );

B = zeros( size( col, 1 ), length( row )); % Allocate memory for storage

% Simple for-loop (this should be vectorized)
% for c = 1:size( B, 2 )
%     for r = 1:size( B, 1 )
%         B( r, c ) = A( row( c ), col( r, c ));
%     end
% end

% Simple for-loop (further vectorization possible)
r = 1:size( B, 1 );
for c = 1:size( B, 2 )
    B( r, c ) = A( row( c ), col( r, c ));
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接