Connect the dots
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Matt Fig
on 10 Mar 2011
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
More Answers (2)
Walter Roberson
on 9 Mar 2011
If you were doing a 2D problem, I would say "find the centroid and sort the points by angle from the centroid to the point".
As, though, you are working in 3D, I don't know at the moment if what you are asking to do always has a solution.
2 Comments
Walter Roberson
on 10 Mar 2011
I was right, what you are asking does not always have a solution.
Consider a set of four points, A(-1,0,0), B(0,1,1), C(1,0,0), and D(0,-1,-1). Create line segments A-B, A-C, B-D, and C-D -- like pushing back the corners of a square. Now, if you are considering point A, should you connect next to point B or point C? You could try defining it in terms of "clockwise" or "counterclockwise", but if you do so then you will notice that what is clockwise looking down the Y axis from +infinity is counter-clockwise looking down the Y axis from -infinity: there is no objective reason to choose one over the other.
The situation is logically similar to being asked to sort a set of 2D points that have complex coordinates.
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!