Filter löschen
Filter löschen

Is it possible to sort an array by making the repeated elements in the last?

2 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Stephen23
Stephen23 am 21 Feb. 2018
Bearbeitet: Stephen23 am 21 Feb. 2018
>> 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 Kommentare
Jan
Jan am 21 Feb. 2018
This sorts in unique, twice in sort and again in ismember. In addition the perfectly working histc is deprecated (what a pity!).
Mohammad Ayoub
Mohammad Ayoub am 21 Feb. 2018
Thank you Stephen and Jan.
Jan I know your answer is true but I think it is a little advanced for me haha, my code is really small and I am still new to MATLAB, so what Stephen wrote works perfectly fine in my application!
By the way, can anyone explain to me what happened exactly (step by step or write the code again with comments) in the code? If you please, so I can understand it better.
Thank you very much!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

KSSV
KSSV am 21 Feb. 2018
A = [-2 -2 -1 3 3] ;
s = sign(A) ;
[val,idx] = sort(abs(A)) ;
iwant = s(idx).*val
  3 Kommentare
KSSV
KSSV am 21 Feb. 2018
What result you expect for [-1 -1 -3 -5 -5]?
Mohammad Ayoub
Mohammad Ayoub am 21 Feb. 2018
The result I expect is [-3 -1 -1 -5 -5] or [-3 -5 -5 -1 -1]
The important thing is that the -3 (which is not repeated) is in the beginning of the array.
By the way, I am limiting my code to 1 repeated value, there will be no more than one repeated element in the arrays (I think this makes it slightly easier)

Melden Sie sich an, um zu kommentieren.


Jan
Jan am 21 Feb. 2018
Bearbeitet: Jan am 21 Feb. 2018
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)];

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by