MATLAB: Ordering rows based on value

intersectloopmatches

Suppose I have a matrix of values as follows:
matches = [1,2;1,4;2,5;3,4;3,6;5,6;];
Is there a way to "connect these rows together based on a common value in the rows column. The desired result is as follows:
connected = [1,2,5,6,3,4,1]

Best Answer

k1 = bsxfun(@minus,matches(:,1),matches(:,2)');
[ii,jj] = find(k1 == 0);
a = unique([ii;jj]);
out1 = unique(matches(a,:)');
f=matches(setdiff(1:6,a),:);
[ff,bb,cc] = unique(f','first');
[~,id] = sort(bb,'descend');
out2 = ff(id);
connected = [out1;out2(2:end)]