How can I reorder paired points

1 view (last 30 days)
Matthew
Matthew on 16 Mar 2015
Answered: BobH on 13 Feb 2020
I have sequence of paired points. The rows need to be reordered in such a way as listed in the "result". Values in col 1 are always smaller than col 2. And the smallest value is always in row1 col1. The order is based on point pairing. These points need to be placed in sequence.
For example in the sample below, look at row3 [4 6]. The following row must have a "6" in the first column, so the row containing the "6" in the first column needs to moved to row 2. And so on down the line. Each sequential row should have one matching value. There will be 2 non matching values, one in first row col 1 and one at the last row col 2.
a=[1 2;2 4;4 6;10 11;11 13;13 15;6 20;20 22;22 24;10 24]
result=[1 2;2 4;4 6;6 20;20 22;22 24;24 10;10 11;11 13;13 15]
Once I have this new order i need to apply to the row movement to another variable. I may be able to do this part as i asked question on it previously, but I think this is different.
Thank you in advance for any help.
  1 Comment
James Tursa
James Tursa on 16 Mar 2015
I assume the last row of "a" is a typo and should be:
a=[1 2;2 4;4 6;10 11;11 13;13 15;6 20;20 22;22 24;24 10]

Sign in to comment.

Answers (2)

James Tursa
James Tursa on 16 Mar 2015
Brute force:
[~,x] = min(a(:,1));
result = zeros(size(a));
m = size(a,1);
result(1,:) = a(x,:);
for k=2:m
f = find(a(:,1)==result(k-1,2),1);
result(k,:) = a(f,:);
end

BobH
BobH on 13 Feb 2020
A different approach... your question made me think of graph theory, and path traversal.
a = [1 2;2 4;4 6;10 11;11 13;13 15;6 20;20 22;22 24;24 10] % altered last row per James
S = sparse(a(:,1)',a(:,2)', true);
b = biograph(S);
% view( b );
p = traverse( b, min(a(:,1)) ); % sequence of nodes, starting from 1
% All entries in p can be found in col 1 of a, except p(end)
p(end) = []; % remove last element of path (the 15)
[~,~,ix] = intersect(p, a(:,1), 'stable');
a(ix,:)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!