n_choose_r function

Henry Gomersall <[email protected]> Fri, 28 Nov 2003 08:29:47 -0600
Newsgroups gmane.comp.gnu.octave.sources
Message-ID <[email protected]>
I have written a function that returns a matrix containing all the
values of n choose r, with the different combinations in the rows.

Its probably not the fastest way of doing it, but its short and does the
job.

its called by n_choose_r(n,r)

Apologies if it already exists.

Henry Gomersall

-- 
Henry Gomersall
Trinity College, Cambridge
Mobile: 07764 756059
[email protected]
http://www.heng.pwp.blueyonder.co.uk/

Please avoid sending me any WORD or POWERPOINT attachments.
See http://www.fsf.org/philosophy/no-word-attachments.html

"If your only contribution is to quote another, that is no contibution
at all."
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;