Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

matlab - Combinations from a given set without repetition

Suppose I have a matrix defined as follows

M = [C1 C2 C3 C4]

Where the C's are column vectors I want some efficient (i.e. no for loops) way of producing A vector such that

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

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That is, what nchoosek 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 it's your intention but nchoosek is Matlabs implementation of The number of k-combinations from a given set S of n elements without repetition (Wikipedia)

The function nchoosek is performance wise not very efficient though. But there are equivalents on File Exchange, which are much(!!) faster and doing the same.


Just to make it clear, it's not just working for the fairly simple example above, and is not returning any indices. It directly transforms the matrix as desired.

M = [ 21 42 123 17 ];

returns:

R =

    21    42
    21   123
    21    17
    42   123
    42    17
   123    17

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...