Combinations from a given set without repeating

Suppose I have a matrix defined as follows:

M = [C1 C2 C3 C4]

Where C are the column vectors I want some efficient (i.e. no for loops) way to create a vector A such that

ResultVec = [C1 C2; 
             C1 C3; 
             C1 C4;
             C2 C3; 
             C2 C4; 
             C3 C4]

Thanks in advance!

+4
source share
2 answers

This is the easiest way:

n = size(M, 2);
[j, i] = ind2sub([n n], find(~triu(ones(n))));
ResultVec = M(:, [i j]);
ResultVec = reshape(ResultVec, [], 2)
+4
source

That is what nchoosekit does:

M = [ 1 2 3 4 ];

R = nchoosek(M,2);

returns:

R =

     1     2
     1     3
     1     4
     2     3
     2     4
     3     4

I don’t know if this is your intention, but it nchoosekis a Matlabs implementation. Number of k-combinations from a given set S of n elements without repetition ( Wikipedia )

nchoosek . File Exchange , (!!) .


, . .

M = [ 21 42 123 17 ];

:

R =

    21    42
    21   123
    21    17
    42   123
    42    17
   123    17
+9

All Articles