How to sort a complex vector with tie breaker angles between [0, 2π)?
Show older comments
By default the sort(A) function sort A by abs(A) when A is complex. If A has elements with equal magnitude, then use angle(A) in the interval (-π,π] to break ties. Therefore, we have the following sorting scheme
since the first vector has the angles
respectively, due to the fact angles are defined in
. I want to convert the tie break angle range to
, so that angles would be
so that we would have the sorting scheme of
.
Things I did:
- I could not find a way to provide a custom comparator function to the sort() function like it can be done in other languages like Python or C++.
- I tried the hectic way of redefining angle() function and adding new definition on top the MATLAB path. When I call the angle() function it calls my definition, but I guess since a compiled version of the built-in sort() function is called, new implementation is not used. I may be missing something here.
Of course, I can write my own mergesort or quicksort implementation with custom comparator function, but I keep thinking there must be a better way to do this.
Accepted Answer
More Answers (2)
How about adding pi to the phase (angle) of each number, sorting, then subtracting pi again (i.e., negate, sort, negate)?
z = [2 -1 1i -1i];
sort(z) % original
-sort(-z) % new
1 Comment
Maybe it helps to sort the rotated values:
a = [2, -1, i, -i];
[~, idx] = sort(-a * 1i);
a(idx)
3 Comments
"since we expect" - I do not think that I really know, what you expect. But I assume you can understand the idea of modifying the data by rotating them instead of inventing a new sorting function.
Unfortunately you have provided a not exhaustive set of inputs in a format, which cannot be used by copy&paste. This makes it tedious to modify the suggested method until it matchs your expectations. But maybe you can adjust this idea to your needs?
What about:
a = [1-1i, 1+1j, -1-1i, -1+1i];
[~, idx] = sort(-a);
a(idx)
Tuna Alikasifoglu
on 2 Nov 2022
Edited: Tuna Alikasifoglu
on 2 Nov 2022
Categories
Find more on Logical 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!.png)