Connect the dots
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Matt Fig
2011 年 3 月 10 日
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
その他の回答 (2 件)
Walter Roberson
2011 年 3 月 9 日
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 件のコメント
Walter Roberson
2011 年 3 月 10 日
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.
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!