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

3 次查看(过去 30 天)
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

回答(2 个)

Stephen23
Stephen23 2019-1-22
编辑:Stephen23 2019-1-22
>> 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 2019-1-22
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

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by