Find row combinations of a 2-dimensional matrix

I have a matrix:

X = [2,6,1; 3,8,1; 4,7,1; 6,2,1; 6,4,1; 7,3,1; 8,5,1; 7,6,1];

I want to find all combinations of X. ie strings

A(1) = [2, 6, 1; 3, 8, 1; 4, 7, 1]
A(2) = [2, 6, 1; 3, 8, 1; 6, 2, 1]
:
:
:

Here is what I tried:

X = [2,6,1; 3,8,1; 4,7,1; 6,2,1; 6,4,1; 7,3,1; 8,5,1; 7,6,1];
p = 3
[m, n] = size(X);
comb = combnk(1:m, p);
[s, t] = size(comb);
c = [X(comb(:,1), :, :) X(comb(:,2), :, :) X(comb(:,3), :, :)];

This gives me a matrix like:

c = 2     6     1     3     8     1     4     7     1
    2     6     1     3     8     1     6     2     1
    2     6     1     3     8     1     6     4     1

I want to apply the concatenate matrix parameter to get c to make it dynamic depending on p value, but I'm not sure how to use it. I do not want to use For loop. Please help me.

+4
source share
3 answers

This is fully vectorized, so it should be fast:

n = 3; %// number of rows to pick each time
ind = reshape(nchoosek(1:size(X,1), n).', [], 1); %'// indices of combinations
A = permute(reshape(X(ind,:).', size(X,2), n, []), [2 1 3]);

Result

A(:,:,1)
ans =
     2     6     1
     3     8     1
     4     7     1

A(:,:,2)
ans =
     2     6     1
     3     8     1
     6     2     1

and etc.

If you need a result in the form of an array of cells, you can convert Afrom a 3D array to an array of cells as follows:

A = mat2cell(A, size(A,1), size(A,2), ones(1,size(A,3)));
+3
source

. . , .

X = [2,6,1; 3,8,1; 4,7,1; 6,2,1; 6,4,1; 7,3,1; 8,5,1; 7,6,1];
p = 3;
%// List all combinations choosing 3 out of 1:8.
v = nchoosek(1:size(X,1), p);
%// Use each row of v to create the matrices, and put the results in an cell array.
%// This is the A matrix in your question.
A = arrayfun(@(k)X(v(k,:), :), 1:size(v,1), 'UniformOutput', false);
%// And you can concatenate A vertically to get c.
flatA = cellfun(@(x)reshape(x, 1, []), A, 'UniformOutput', false);
c = vertcat(flatA{:});

PS: , , A, . , c , .

: arrayfun cellfun .

+2

, reshape , Matlab :

c = reshape(X(comb',:)',9,[])'

:

A = permute(reshape(X(comb',:)',3,3,[])', [2,1,3])
+1

All Articles