MATLAB: Connect the dots

lineMATLABmatrixrowswap

I have a matrix that is (m,6) big. Each row of this matrix represents a unique line segment and columns 1:3 have the XYZ1 coordinates of that line and columns 4:6 have the XYZ2 coordinates of that line. How do I reorganize the matrix such that the first 3 columns of the next row is equal to the last three columns of the previous row? All the lines (represented by the matrix rows) connect to each other and I want to sort the matrix so that the end of the first line is the beginning of the next line. In other words, I'd like to keep the elements of the same row of the matrix together, but I may have to swap columns 1:3 with 4:6 in that row. Make sense? I hope so because I'm stuck on how to program this.
Thanks.
Thanks

Best Answer

This problem might be solved more easily and efficiently, but this solution should get you through your example.
Walter's concerns are valid, and it may just take your seeing an example without a solution, which you thought for sure had one, to see what he means.
G = [1 2 3 4 5 6; 4 5 7 4 5 6; 1 2 7 1 2 3; 4 5 7 1 2 7]
L = size(G,1);
for ii = 2:L
T = ismember(G(ii:L,1:3),G(ii-1,4:6),'rows');
T2 = ismember(G(ii:L,4:6),G(ii-1,4:6),'rows');
if any(T)
idx = find(T)+ii-1;
tmp = G(idx,:);
G(idx,:) = G(ii,:);
G(ii,:) = tmp;
elseif any(T2)
idx = find(T2)+ii-1;
tmp = G(idx,:);
G(idx,:) = G(ii,:);
G(ii,:) = tmp;
G(ii,4:6) = G(ii,1:3);
G(ii,1:3) = G(ii-1,4:6);
else
error('No solution')
end
end
G