Matlab nchoosek problem

2019-07-04 02:46发布

问题:

My question is Matlab related. There exist a fnct named nchoosek([vector],integer). By using this function I would like to get all 2-elements combinations of the given vector. (i.e nchoosek([1:10000, 2])). This is very slow, as stated in matlab documentation.

The question is : "Is there a faster way to do the same job?".

Thank you for your time I really appreciate your efforts.

回答1:

If it's only 2-element combinations you need, you can use NDGRID. Note that all two-element combinations up to N require N^2 values, so if Matlab starts paging, the process will be slow.

N = 100;
[xx,yy] = ndgrid(1:N,1:N);
allCombinations = [xx(:),yy(:)];

Please be aware that the function NDGRID differs significantly from nchoosek. The former returns a double-row vector with all possible N^2 combinations, while the latter is leaving out combinations of two times the same element, as well as combinations where just the order is changed. Leading to just (N^2-N)/2 row elements.