Reputation: 145
I have a vector x
with complex entries and I want to do the following:
Let's say there are entries with the same absolute value, for example 13
, 5+12i
and 5-12i
. If I put those in the builtin sort
function, it will put 13
at first, then 5-12i
and then 5+12i
. However, since all of those have the same magnitude, I want to sort them by their imaginary part, so I would like to have 5-12i
come first, then 13
and then 5+12i
. What is the easiest way of doing this, without using any loops or if statements?
Upvotes: 1
Views: 47
Reputation: 65430
You can construct a matrix that has the magnitude as the first column and the imaginary component as the second column and then use sortrows
to sort the result which will sort first by the first column (the magnitude) and then by the second column (the imaginary component). You can use the second output of sortrows
to get the corresponding indices of the sorted rows which you can then use to sort the original data.
data = [13, 5+12i, 5-12i];
[~, inds] = sortrows([abs(data(:)), imag(data(:))]);
sorted = data(inds);
% 5.0000 - 12.000i 13.0000 + 0.0000i 5.0000 +12.0000i
Upvotes: 4