Reputation: 41
I'm trying find all combinations of an n-by-n matrix without repetitions.
For example, I have a matrix like this:
A = [321 319 322; ...
320 180 130; ...
299 100 310];
I want the following result:
(321 180 310)
(321 130 100)
(319 320 310)
(319 139 299)
(322 320 100)
(322 180 299)
I have tried using ndgrid
, but it takes the row or the column twice.
Upvotes: 4
Views: 3177
Reputation: 32920
Here's a simpler (native) solution with perms
and 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
The result is a matrix, each row containing a different combination of elements:
C =
321 180 310
319 320 310
321 130 100
319 130 299
322 320 100
322 180 299
This solution can also be shortened to:
C = A((perms(1:N) - 1) * N + meshgrid(1:N, 1:factorial(N)))
Upvotes: 2
Reputation: 350
You can use perms
to permute the columns as follows:
% 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
Upvotes: 0
Reputation: 14361
ALLCOMB
is the key to your question
E.g. I am not front of a MATLAB machine so, I took a sample from web.
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
Upvotes: 0