It is not clear from your explanations, but I assume:
- All the rows in
M
are unique. - Seek for the combinations of rows
M
where no number occurs twice. - The length of each combination is
floor(max(M(:))/2)*2
.
Then using recursion, this should work.
function [ U ] = searchappend( R,M, d, max_d )
% termination criteria
if d==max_d
U=R;
return;
end
lM = length(M(:,1));
k=0;
U = [];
% seek for the row to append
for i=1:lM
if sum(ismember(M(i,:),R))==0
S = [R,M(i,:)];
T = searchappend(S, M(i+1:end,:), d+1, max_d);
if k==0 && (~isempty(T))
k=k+1;
U = [U;T];
end
end
end
end
_____________
lM = length(M);
n = floor(max(M(:))/2);
A = [];
for i=1:(lM-n+1)
R = M(i,:);
T = searchappend(R,M(i+1:end,:),1,n);
if ~isempty(T)
A = [A;T];
end
end
Note that I did not optimize it so it may be slow. The complexity should be O(n!) where n is the number of rows in M.