Is it possible to sort an array by making the repeated elements in the last?
1 次查看(过去 30 天)
显示 更早的评论
Greetings.
Consider a vector A = [-2 -2 -1 3 3], is it possible to sort this vector (a generalized method) to [-1 -2 -2 -3 -3]?
The only thing that matters is that the repeated elements are in the last, it doesn't matter what way the repeated elements themselves are sorted (for example, [-1 -2 -2 -3 -3] or [-1 -3 -3 -2 -2] are fine) I just want the distinct value to be on the left before any repeated value.
Thank you in advance,
M. Ayoub
0 个评论
采纳的回答
Stephen23
2018-2-21
编辑:Stephen23
2018-2-21
>> A = [-2,-2,-1,3,3,3,9,9,0,99]
A =
-2 -2 -1 3 3 3 9 9 0 99
>> [cnt,idx] = histc(A,unique(A));
>> [~,idy] = sort(cnt>1);
>> [~,idz] = ismember(idx,idy);
>> [~,ids] = sort(idz);
>> B = A(ids)
B =
-1 0 99 -2 -2 3 3 3 9 9
And
>> A = [-1,-1,-3,-5,-5]
...
B =
-3 -5 -5 -1 -1
2 个评论
Jan
2018-2-21
This sorts in unique, twice in sort and again in ismember. In addition the perfectly working histc is deprecated (what a pity!).
更多回答(2 个)
Jan
2018-2-21
编辑:Jan
2018-2-21
A = [-1 -1 -3 -5 -5];
[b, n] = RunLength(sort(A));
m = (n == 1);
result = [b(m), RunLength(b(~m), n(~m)];
If you do not have a C-compiler installed, use RunLength_M from this submission.
Maybe this is faster:
sA = sort(A);
[b, n, index] = RunLength(sA);
mask = false(size(A));
mask(index(n == 1)) = true;
result = [sA(mask), sA(~mask)];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!