domingo, 18 de julho de 2010

Combination

Here is a simple function for Octave/MatLab I wrote to create the combinations of the numbers in a vector. Suppose you want to get the possible combinations of the numbers [1 2 3 4] arrenged in 3, what would give you [1 2 3], [1 2 4], [1 3 4] and [2 3 4]. You just have to use the function bellow calling X = combinations([1 2 3 4],3), and X will be the matrix with all combinations.


function X = combinations(x,k)
%
% X = combinations(x,k)
% Create all combinations (without repetition) of the
% elements in x arragend in groups of k items.
% example:
% x=[1 2 3 4];
% X = combinations(x,3)
% X =
% 1 2 3
% 1 2 4
% 1 3 4
% 2 3 4
%

if(size(x,1) > size(x,2)), x = x'; end;
n = length(x);
X = [];
if(k == 1),
X = x';
else
for l = 1 : n-k+1,
C = nchoosek(n-l,k-1);
xtemp = x;
xtemp(1:l) = [];
X = [X; [repmat(x(l),C,1) combinations(xtemp,k-1)] ];
end;
end;

Nenhum comentário:

Postar um comentário