Ordering data based on previous data value

Hello,
I have two columns of data as below:
Column 1 Column 2
39.28 12.45
42.85 0.00
48.14 0.00
53.67 9.21
42.80 16.09
0.00 0.00
Starting ith the data in row 6 (0.00 0.00), how can I select the row of data which contains the number in column 1 that is closest to 0 i.e.
0.00 0.00, 39.28 12.45
Then, once I've found the above, I then need to find the next row of data using Column 1 data that is closest to 12.45 i.e.
0.00 0.00, 39.28 12.45, 42.80 16.09
And then so on and so on until I get:
0.00 0.00, 39.28 12.45, 42.80 16.09, 42.85 0.00, 53.67 9.21.
There can be no repeat rows of data.
Many thanks,
Phil

4 Comments

Do you need to maintain the current order of the data? This would be fairly easy if you just sorted with sortrows() and then progress from top to bottom.
I don't need to maintain the order of the columns. I just need to order the data as above.
For example:
Ignore 0,0 for now and select the row with the smallest number in column 1 - 39.28 12.45.
Then, using the number in the second column from the row of data printed above as the datum (12.45) find the row with the number in column 1 that is closest to the datum of 12.45 - this is 42.80, 16.09.
Then, using the number in the second column from the row of data printed above as the datum (16.09) find the row with the number in column 1 that is closest to the datum of 16.09 - this is 42.85 0.00.
This progresses until all the rows have been ordered to show:
0.00 0.00, 39.28 12.45, 42.80 16.09, 42.85 0.00, 53.67 9.21
Comments and solutions are appreciated.
Many thanks,
Phil
I'm confused how you went from 16.09 to 0.00, rather than 9.21.
I think that you should look at sortrows().
Hello,
I have managed to get sortrows to work so my problem is now solved.
Many thanks,
Phil

Answers (1)

You will have to use an iterative method to do what you want.
m = [39.28 12.45; 42.85 0.00; 48.14 0.00; 53.67 9.21; 42.80 16.09; 0.00 0.00] %demo data
sortedm = zeros(size(m));
lastval = 0;
for destrow = 1:size(m, 1)
[~, moverow] = min(abs(m(:, 1) - lastval));
sortedm(destrow, :) = m(moverow, :);
lastval = m(moverow, 2);
m(moverow, :) = [];
end
You may be able to avoid the iterative deletion of elements (most likely the slowest part of the algorithm) by using a logical array as a row filter but you'd have to relate the location of filtered rows to the full array.

This question is closed.

Tags

Asked:

on 3 Dec 2018

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!