Based on the final solution @Jan proposed, I noticed a simple modification that can fix the problem. Since the angle() function produces angles between (-π,π], and since
angle(-1)
ans = 3.1416
which is π. By writing (-a), we basically shift the interval by π, which results in the interval (0,2π]. Hence, the real values end up with 2π angles, which are larger than every other angle. However, we want to have [0,2π) interval (or equivalently (-2π,0] interval). This can be achieved by -π shift, i.e., writing . Even though they are mathematically equivalent, we ensure that the angle is -π as:
angle(exp(-1j * pi))
ans = -3.1416
Hence, with this slight modification to the latest proposal of @Jan, we can sort a complex vector with tie breaker angles between [0,2π) as follows:
a = [0, -1j, 1j, 1, -1, 1-1j, 1+1j, -1-1j, -1+1j, -4+3j, 3+4j];
b = [0, 1, 1j, -1, -1j, 1+1j, -1+1j, -1-1j, 1-1j, 3+4j, -4+3j];
[~, idx] = sort(exp(-1j * pi) * a);
sorted = a(idx)
sorted =
0.0000 + 0.0000i 1.0000 + 0.0000i 0.0000 + 1.0000i -1.0000 + 0.0000i 0.0000 - 1.0000i 1.0000 + 1.0000i -1.0000 + 1.0000i -1.0000 - 1.0000i 1.0000 - 1.0000i 3.0000 + 4.0000i -4.0000 + 3.0000i
all(sorted == b)
ans = logical
1