2012-12-07 204 views
4

我試圖找到一個n乘n矩陣不重複的所有組合。matlab中的矩陣的所有組合

例如,我有一個這樣的矩陣:

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

+0

請包括一些代碼來顯示 [你嘗試過什麼(http://whathaveyoutried.com) –

回答

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 
+0

如果輸入參數'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 
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)))