Combination

PURPOSE ^

produces the array of combinations possible picking k from n

SYNOPSIS ^

function [out] = Combination(n,k)

DESCRIPTION ^

 produces the array of combinations possible picking k from n
 adapted from Combinadics
 http://msdn.microsoft.com/en-us/library/aa289166(VS.71).aspx

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

SUBFUNCTIONS ^

SOURCE CODE ^

0001 function [out] = Combination(n,k)
0002 % produces the array of combinations possible picking k from n
0003 % adapted from Combinadics
0004 % http://msdn.microsoft.com/en-us/library/aa289166(VS.71).aspx
0005 
0006     if (n < 0 || k < 0) % normally n >= k
0007       disp('Negative parameter in constructor');
0008       return
0009     end
0010     
0011     data(k) = 0;
0012     for i = 1:k;
0013       data(i) = i;
0014     end
0015    % Combination(n,k)
0016     out.choose = getNumberCombinations(n,k);
0017    
0018    % determine the combinations
0019    for i = 1:out.choose
0020        out.all(:,i) = getCombination(n,k,i-1);
0021    end
0022 return;
0023 
0024 function [m] = getNumberCombinations(n,k)
0025    % find number of combinations by choose k items from n
0026     if (n < k)
0027       m = 0;  % special case
0028     else
0029         if (n == k)
0030             m = 1;
0031         else
0032             m = factorial(n) / (factorial(k) * factorial(n-k)); 
0033         end
0034     end
0035     
0036 return;
0037 
0038 function [c] = getCombination(n,k,index)
0039     c(1) = 1;
0040     x = 1;
0041     for i = 1:n
0042         if (k == 0)
0043             return;
0044         end
0045     
0046         threshold = getNumberCombinations(n-i,k-1);
0047         %disp(sprintf('index = %d, threshold = %d',index,threshold));
0048         if (index < threshold)
0049             c(x) = i;
0050             x = x+1;
0051             k = k-1;
0052         else
0053             if (index >= threshold)
0054                 index = index - threshold;
0055             end
0056         end
0057     end
0058 return;
0059

Generated on Thu 21-Jun-2012 15:39:23 by m2html © 2003