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,但它需要行或列两次。

4

3 回答 3

2

这是一个更简单的(本机)解决方案,其中permsand 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)))
于 2012-12-07T19:34:43.973 回答
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
于 2012-12-07T10:08:38.207 回答
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
于 2012-12-07T12:12:20.847 回答