MATLAB: Convert complex-valued sorted vector with absolute-value repetitions into a cell array

cell arrayscomplex-valuedsorting

I have a very large vector (vC) of complex-valued entries (say mx1). I am sorting this vector (ascending or descending doesn't matter), and I keep track of the index of the entries as follows:
[sorted_Vc, ind_sorted_Vc]=sort(vC);
I am using the magnitude of the complex-valued entries to count the number of elements that have the same magnitude as follows:
abs_sorted_Vc=abs(sorted_Vc);
tt=unique(abs_sorted_Vc);
count=histc(abs_sorted_Vc, tt);
I need to save the sorted result in a cell array such that the rows represent the sorted unique absolute values as given by tt above. Further, in each row I would like to have a number of columns that include the complex-valued entries that correspond to the particular magnitude. I will also need to keep track of the indices of these entries given by ind_sorted_Vc above. To keep track of the indices, I can use another cell array of the same size as the desired complex-valued cell array.
I was able to program this in Matlab without using the above Matlab functions, however, since I am dealing with very big vector sizes on the order of 1 million entries or more, my program is so slow.
I thought through using the built-in Matlab functions such as those provided above, I might be able to efficiently implement it. Any ideas on how should I proceed further.
Thanks.

Best Answer

abs_sorted_Vc = abs(sorted_Vc);
[tt, tt_a, tt_b] = unique(abs_sorted_Vc);
Q = accumarray(tt_b(:), sorted_Vc(:), [], @(x) {length(x); x(:)});
This returns a cell array, each element of which is a column vector, the first element of which is the length of the vector, and the remaining elements are the complex values. The length does not really need to be stored as it can be reconstructed via cellfun(@length,Q) but I decided to leave it in anyhow for illustrative purposes.
The index values found in tt_b could also be stored during the accumarray operation, requiring extra complexity. For example,
Q = accumarray([tt_b(:); tt_b(:)], [tt_b(:); sorted_Vc(:)], [], @(x) {x(:)});
Then the first half of the elements in each cell would be indices and the second half would be corresponding values.