Sort elements of an array with a given a priority, keeping track of indexes (includes repeated elements)

6 Ansichten (letzte 30 Tage)
Hi,
I would like to sort an array vR = [1.5 2 1.25 3 3.5 5 8 2.359 3] with the following rules:
  1. Sorted integers
  2. Sorted half integers
  3. Sorted quarter integers
  4. Remaining sorted elements
After the sort is completed, I want to know the indexes of elements in the new array relative to the previous unsorted array.
Note: there can be repeated elements
vR_sorted = [2 3 3 5 8 1.5 3.5 1.25 2.359]
idxs = [2 4 9 6 7 1 5 3 8]
Thanks

Antworten (2)

Stephen23
Stephen23 am 22 Jan. 2019
Bearbeitet: Stephen23 am 22 Jan. 2019
>> vR = [1.5,2,1.25,3,3.5,5,8,2.359,3]
vR =
1.5000 2.0000 1.2500 3.0000 3.5000 5.0000 8.0000 2.3590 3.0000
>> [~,idx] = sortrows([bsxfun(@mod,vR(:),[1,0.5,0.25])~=0,vR(:)])
idx =
2
4
9
6
7
1
5
3
8
>> vS = vR(idx)
vS =
2.0000 3.0000 3.0000 5.0000 8.0000 1.5000 3.5000 1.2500 2.3590
For MATLAB versions R2016b and later bsxfun is not required:
[~,idx] = sortrows([mod(vR(:),[1,0.5,0.25])~=0,vR(:)])

Kevin Phung
Kevin Phung am 22 Jan. 2019
There might be something more elegant than my for-loop, but this should work. Let me know!
vR = [1.5 2 1.25 3 3.5 5 8 2.359 3 ];
integers = vR(floor(vR) ==vR); % rule 1
a = vR(not(ismember(vR,integers))); %NOT integers
half_int = a(floor(a - .5) == a-.5); %half integers
b = a(not(ismember(a,half_int))); % NOT half integers
list1 = b(floor(b - .25) == b-.25);
list2 = b(floor(b-.75) == b-.75);
quarter_int = [list1 list2];
leftOvr = b(not(ismember(b,quarter_int))); % remaining
sorted_vR = [sort(integers) sort(half_int) sort(quarter_int) leftOvr];
idx =[];
for i = 1 :numel(vR)
if any(ismember(vR,sorted_vR(i)))
idx1 = find(ismember(vR,sorted_vR(i)));
idx = [idx idx1]; % this will add in duplicates
end
end
idx = unique(idx,'stable'); % remove duplicate indices

Kategorien

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

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by