All combinations for matrix in matlab

I am trying to find all combinations of an n-on-n matrix without repetition.

For example, I have a matrix like this:

A = [321 319 322; ... 320 180 130; ... 299 100 310]; 

I want to get the following result:

(321 180 310)
(321 130 100)
(319 320 310)
(319 139 299)
(322 320 100)
(322,180,299)

I tried using ndgrid , but it takes up a row or column twice.

+4
source share
3 answers

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 contains 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))) 
+2
source

ALLCOMB - the key to your question

eg. I am not in front of the MATLAB machine, so I took a sample from the Internet.

 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
source

You can use perms to swap columns as follows:

 % A is given mxn 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 
0
source

All Articles