File Exchange

image thumbnail


version 1.0 (1.54 KB) by

All combinations of N elements taken two at the time.



View License

Usage - vec=nCtwo(dat) where dat is a vector of length N, produces a matrix with N*(N-1)/2 rows and 2 columns. Each row of the result vec has two of the elements in the vector dat. Similar to the MATLAB function NCHOOSEK(dat,2) but much faster.

Comments and Ratings (4)

John D'Errico

Interestingly, I can do better than the triu code, still in an entirely vectorized solution. The code below has no additional memory allocation. But it is no faster than the other versions. According to profile, most of the time consumed is mainly in the very last line, just the simple lookup.

function IJ = nc2(nvec)
nvec = nvec(:);
n = length(nvec);
IJ = ones(n*(n-1)/2,1)*[0 1];
ind = cumsum([1;((n-1):-1:2)']);
IJ(ind,1) = 1;
IJ(1,2) = 2;
IJ(ind(2:end),2) = 2+((1-n):1:-2)';
IJ = nvec(cumsum(IJ,1));

Jos x@y.z

As for the present submission, it is pretty good and indeed fast. It contains help (including a H1 line). It unfortunately lacks internal comments and examples, and can be improved in this respect.

The following version of JD's excellent engine directly returns the rightly order output, and is a little less memory consuming (2*N-1 elements less...) :
[c2,c1] = find(tril(ones(numel(x)-1)));
y = x([c1(:) c2(:)+1]);

I have just submitted my own fast, vectorized alternative of nchoosek(x,2) to the FEX, which is also not memory consuming.

Simone Scaringi

Very clever and elegant solution John!

However when dealing with large N the step

[I,J] = find(triu(ones(length(nvec)),1));

requires lot's of ram, and nCtwo.m performs faster (even for small N)...

I know for loops are not appropriate within matlab, however one has to include some when dealing with big datasets...


John D'Errico

Cleaner is just this simple solution.

[I,J] = find(triu(ones(length(nvec)),1));
IJ = [I(:),J(:)];
IJ = nvec(IJ);

MATLAB Release
MATLAB 7 (R14)

Inspired: VChooseK, NCHOOSE2

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Win prizes and improve your MATLAB skills

Play today