sorting non-exact x/y data into rows and columns, typewriter style
2 views (last 30 days)
Show older comments
say I have the following two arrays:
x=[1.01 2.01 1.02 2.02];
y=[1.01 1.02 2.01 2.02];
sorting these rows using
xy = table(x',y')
[~, id] = sortrows(xy)
gives the answer of
id = [1;3;2;4];
I'm hoping to obtain the 'typewriter' answer of
id = [3, 4; 1, 2]
or something similar that tells me the third element of the table is the upper left, etc. The eventual goal is to combine elevation .tiff in the correct order to form a coherent dataset from northwest to southeast.
I feel like this should be a simple solution, but I'm delving into loops and logic and feel like I'm missing something easy.
Thanks in advance.
3 Comments
Accepted Answer
Stephen23
on 27 Apr 2024
x = [1.01,2.01,1.02,2.02];
y = [1.01,1.02,2.01,2.02];
m = [x(:),y(:)]; % simpler
[~,id] = sortrows(round(m),[-2,+1])
2 Comments
Stephen23
on 27 Apr 2024
Edited: Stephen23
on 27 Apr 2024
"I feel like this should be a simple solution, but I'm delving into loops and logic and feel like I'm missing something easy."
There is no "simple solution" because your problem is ill-defined. The cause becomes clearer when we plot with larger fractional values. Here I increased .01=>.2 and .02=>.4:
x = [1.2,2.2,1.4,2.4];
y = [1.2,1.4,2.2,2.4];
axis();
xlim([1,3])
ylim([1,3])
for k = 1:numel(x)
text(x(k),y(k),sprintf("%d",k))
end
You stated that "I'm hoping to obtain the 'typewriter' answer of id = [3, 4; 1, 2]", but we can see that this corresponds to neither an asending nor descending sort in either dimension. The SORTROWS documentation explains why this is significant: "When the first column contains repeated elements, sortrows sorts according to the values in the next column and repeats this behavior for succeeding equal values." In other words, any ties (i.e. equal values) are distinguished by sorting the remaining columns**. However, your data does not have any equal values! Look at your data: all of those values are different, which means SORTROWS will ultimately just be equivalent to sorting by the primary column that you select in whatever order you select. And that will not give you the index order that you want.
The answer I gave you assumes that you want to consider the "similar" values as being equivalent, and clusters them using ROUND into sets of equal values. But how "similar" are the values allowed to be in order to belong to one cluster? Until you define the problem clearly, there is no general solution.
** This basic concept applies to most any sorting algorithm that repeatedly applies stable sorts to a data set.
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!