Re: n_choose_r function

Tomer Altman <[email protected]> Fri, 28 Nov 2003 18:39:10 -0800 (PST)
Newsgroups gmane.comp.gnu.octave.sources
Message-ID <[email protected]>
You may be interested in these Octave-Forge packages:

http://octave.sourceforge.net/index/f/nchoosek.html

http://octave.sourceforge.net/index/f/perms.html

HTH,

~Tomer


On Nov 28, 2003 at 8:29am, Henry Gomersall wrote:

whg21 >Date: Fri, 28 Nov 2003 08:29:47 -0600
whg21 >From: Henry Gomersall <[email protected]>
whg21 >To: [email protected]
whg21 >Subject: n_choose_r function
whg21 >Resent-Date: Fri, 28 Nov 2003 15:46:41 -0600
whg21 >Resent-From: [email protected]
whg21 >Resent-To: octave sources mailing list
whg21 >    <[email protected]>
whg21 >
whg21 >I have written a function that returns a matrix containing all the
whg21 >values of n choose r, with the different combinations in the rows.
whg21 >
whg21 >Its probably not the fastest way of doing it, but its short and does the
whg21 >job.
whg21 >
whg21 >its called by n_choose_r(n,r)
whg21 >
whg21 >Apologies if it already exists.
whg21 >
whg21 >Henry Gomersall
whg21 >
whg21 >
n_choose_r.m (text/plain, 819 B)
	1;

function [comb_matrix, row] = calc_comb(comb_matrix, row, column, start, n, r)
	
	%while still room in columns above to hold values up to n...
	while(start <= n-(r-column));

		comb_matrix(row, column) = start;

		if(column < r);
			[comb_matrix, row] = calc_comb(comb_matrix, row, column+1, start+1, n, r);
		endif;
			
		++start;
		if(start <= n-(r-column))
			++row;
			idx = column-1;

			%copy previous row if working above first column
			while(idx>0);
				comb_matrix(row, idx) = comb_matrix(row-1, idx);
				--idx;
			endwhile;
		endif;

	endwhile;
endfunction;

function comb_matrix = n_choose_r(n, r);
	number_rows = factorial(n)/(factorial(r)*factorial(n-r));
	number_columns = r;

	comb_matrix = zeros(number_rows, number_columns);
	
	comb_matrix = calc_comb(comb_matrix, 1, 1, 1, n, r);

endfunction;