Code covered by the BSD License  

Highlights from
comb

comb

by

 

Quickly generate all combination of integers up to specified value in each dimension

comb_arr=comb(p,start)
function comb_arr=comb(p,start)
% comb -- Quickly generate all combinations
%	Usage
%		comb_arr=comb(p)
%		comb_arr=comb(p,start)
%	Input:
%		p		-	Array of maximum value for each dimension
%		start	-	Starting value (scalar). Same for each dimension. Defaults to 
%					1 if not specified
%	Output:
%		comb_arr-	Array of combinations
%	
%	Description:
%	Create all combinations from 'start' to 'p(d)' in each dimension.
%	
%	Ex: comb([1 3 2],1):
%	  1     1     1
%     1     2     1
%     1     3     1
%     1     1     2
%     1     2     2
%     1     3     2
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if(nargin==1)
	%No start given. Default to 1
	start=1;
end
if(min(p)<start)
	error('ERROR: Cannot have "start" be greater than the smalles p(s)');
end

ndim=size(p,2);
mx_arr=p+1-start;
N=prod(mx_arr);

comb_arr=zeros(N,ndim); %Preallocate

for d=1:ndim
	mx=mx_arr(d);
	count=N/mx;
	
	rep=prod(p(1:d-1)+1-start); % sets to 1 for d==1
	
	arr=repmat(start:p(d),rep,N/(rep*mx));
	comb_arr(:,d)=arr(:);
end

Contact us