% combinations( v, n) - generate combinatorial matrix
% where each column contains elements of row vector v taken n at a time.
%
function c = combinations( v, n)

if( n == 1)	% R combinations are just v
  c = v;
  return;
end

m = size(v,2);	% columns(v)

if( m < n)
  error( 'combinations: m >= n is required.');
  return;
end

if( n == m)	% 1 combination is just v' itself
  c = v';
  return;
end

R = prod(n+1:m) / prod(1:m-n);	% number of combinations == columns(c)

c = zeros( n, R);
vnext = v;
i = 1;

while( i <= R)
  cnext = combinations( vnext(2:m), n-1);
  k = size(cnext,2);
  c(:,i:i+k-1) = [vnext(1)*ones(1,k); cnext];
  vnext = vnext(2:m);
  m = m - 1;
  i = i + k;
end
